From 869ae645a2a7f5bcb050ece530b88cfe4355f022 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 16 Sep 2014 19:45:13 +0400 Subject: [PATCH 01/30] created sample branch --- .../fivt/students/Oktosha/helloworld/HelloWorld.java | 1 + .../fizteh/fivt/students/test/shell/ShellMain.java | 12 ------------ 2 files changed, 1 insertion(+), 12 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java delete mode 100644 src/ru/fizteh/fivt/students/test/shell/ShellMain.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java b/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java new file mode 100644 index 000000000..cb42696a1 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java @@ -0,0 +1 @@ +I don't know java now :-( \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/test/shell/ShellMain.java b/src/ru/fizteh/fivt/students/test/shell/ShellMain.java deleted file mode 100644 index c7e6ea78f..000000000 --- a/src/ru/fizteh/fivt/students/test/shell/ShellMain.java +++ /dev/null @@ -1,12 +0,0 @@ -package ru.fizteh.fivt.students.test.shell; - -/** - * @author test - */ -public class ShellMain { - - public static void main(String[] args) { - System.out.println("not working"); - System.exit(1); - } -} From b487897693b9c843244042026aef6374881101cd Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 17 Sep 2014 18:42:27 +0400 Subject: [PATCH 02/30] created directory for shell --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 0 src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java | 1 - 2 files changed, 1 deletion(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java delete mode 100644 src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java new file mode 100644 index 000000000..e69de29bb diff --git a/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java b/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java deleted file mode 100644 index cb42696a1..000000000 --- a/src/ru/fizteh/fivt/students/Oktosha/helloworld/HelloWorld.java +++ /dev/null @@ -1 +0,0 @@ -I don't know java now :-( \ No newline at end of file From 97ddde113f1071c6fb7ab9a5390577d2dfa95df0 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 17 Sep 2014 20:27:23 +0400 Subject: [PATCH 03/30] added helloworld code to shell --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index e69de29bb..942fb526f 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -0,0 +1,8 @@ +package ru.fizteh.fivt.students.Oktosha.Shell; + +public class Shell +{ + public static void main(String args[]) { + System.out.println("Hello, world!"); + } +} From a20e495d056de1c1c9df27f5f7a6c920cbb02427 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 17 Sep 2014 21:38:27 +0400 Subject: [PATCH 04/30] added simple javadoc comment --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 942fb526f..4d409ae03 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,5 +1,9 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +/** + * The Shell class implements an application which partially emulates UNIX command line + */ + public class Shell { public static void main(String args[]) { From dfeb9c14336b239d345969fde4148b467d1fb4a2 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 17 Sep 2014 22:32:28 +0400 Subject: [PATCH 05/30] Managed to write a source that checkstyle accepts. --- .../fivt/students/Oktosha/Shell/Shell.java | 20 +++++++++++++++---- .../students/Oktosha/Shell/package-info.java | 5 +++++ 2 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Shell/package-info.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 4d409ae03..aaa41c29d 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,12 +1,24 @@ package ru.fizteh.fivt.students.Oktosha.Shell; /** - * The Shell class implements an application which partially emulates UNIX command line + * The Shell class implements an application, + * which partially emulates UNIX command line. */ -public class Shell -{ - public static void main(String args[]) { +public final class Shell { + + /** + * This is a private constructor, which is never called. + */ + private Shell() { } + + /** + * + * @param args are treated as shell commands + * if no arguments are given + * Shell runs in interactive mode + */ + public static void main(final String[] args) { System.out.println("Hello, world!"); } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/package-info.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/package-info.java new file mode 100644 index 000000000..47dc1c153 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/package-info.java @@ -0,0 +1,5 @@ +/** + * Created by Daria Kolodzey from group #394. + * Shell package is my solution for the first task. + */ +package ru.fizteh.fivt.students.Oktosha.Shell; From af89b8617c0ca84f4d0ecd84197e46e6c24eeafb Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 22 Sep 2014 12:56:46 +0400 Subject: [PATCH 06/30] added \n at the end of file --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index aaa41c29d..60bc787f7 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -14,11 +14,11 @@ private Shell() { } /** * - * @param args are treated as shell commands - * if no arguments are given - * Shell runs in interactive mode + * @param args command line arguments are treated as shell commands + * if no arguments are given Shell runs in interactive mode */ public static void main(final String[] args) { System.out.println("Hello, world!"); } } + From 6caba8eb92fa6c5ade43670c17f6c84a9b0e78e1 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 30 Sep 2014 15:51:43 +0400 Subject: [PATCH 07/30] Added some code to shell, needs rewriting --- .../fivt/students/Oktosha/Shell/Shell.java | 130 +++++++++++++++++- 1 file changed, 124 insertions(+), 6 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 60bc787f7..73c00ab46 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,24 +1,142 @@ package ru.fizteh.fivt.students.Oktosha.Shell; + +import java.nio.file.Path; +import java.nio.file.Paths; + /** * The Shell class implements an application, * which partially emulates UNIX command line. */ - public final class Shell { - /** - * This is a private constructor, which is never called. + * In this class params to run command are stored. */ - private Shell() { } + class Command { + /** + * Constructor + * + * @param cmdVal will be assigned to cmd + * @param argsVal will be assigned to args + */ + public Command(final String cmdVal, final String[] argsVal) { + cmd = cmdVal; + args = argsVal; + } + + /** + * Cmd setter. + * + * @param str the value to set to cmd + */ + public void setCmd(final String str) { + cmd = str; + } + + /** + * Args setter. + * + * @param strArray the value to set to args + */ + public void setArgs(final String[] strArray) { + args = strArray; + } + + /** + * Cmd getter. + * + * @return actual value of cmd + */ + public String getCmd() { + return cmd; + } + + /** + * Args getter. + * + * @return actual value of args + */ + public String[] getArgs() { + return args; + } + + /** + * The name of command is stored in cmd. + */ + private String cmd; + /** + * The arguments passed to command are stored in args. + */ + private String[] args; + } /** - * * @param args command line arguments are treated as shell commands * if no arguments are given Shell runs in interactive mode */ public static void main(final String[] args) { - System.out.println("Hello, world!"); + workingDirectory = Paths.get("."); + if (args.length == 0) { + interactiveMode(); + } else { + packageMode(args); + } + } + + /** + * The method which implements interactive mode of Shell. + */ + private static void interactiveMode() { + System.out.print("$"); + } + + /** + * The method which implements package mode of Shell. + * + * @param args are command line arguments which are treated as commands + */ + private static void packageMode(final String[] args) { + System.out.println("package"); + String commandString = ""; + for (String s : args) { + commandString = commandString.concat(" "); + commandString = commandString.concat(s); + System.out.println(s); + } + System.out.print(commandString); + } + + /** + * Command pwd prints current working directory. + */ + private static void pwd() { + System.out.println(workingDirectory.toAbsolutePath().normalize()); + } + + /** + * a method which parses string with commands and returns array of Command. + * + * @param str contains commands which the user entered. + * @return array of commands. + */ + /* private Command[] parseCommandString(final String str) { + String[] splitBySemicolon = str.split(";"); + Command[] ans = new Command[splitBySemicolon.length]; + for (String cmd : splitBySemicolon) { + String[] cmdParsed = cmd.split("\\s"); + + } + }*/ + + /** + * A variable holding current working directory. + */ + private static Path workingDirectory; + + /** + * This is a private constructor, which is never called. + */ + private Shell() { } } From 5aa7efd647d315c5f33cb329ded09a3cbf6b7002 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 30 Sep 2014 15:55:16 +0400 Subject: [PATCH 08/30] deleted everything exept my source from the branch Shell --- LICENSE | 24 --------- README.md | 22 -------- build.xml | 59 --------------------- github-workflow.md | 16 ------ tasks/01-Calculator.md | 19 ------- tasks/01-Shell.md | 113 ----------------------------------------- 6 files changed, 253 deletions(-) delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 build.xml delete mode 100644 github-workflow.md delete mode 100644 tasks/01-Calculator.md delete mode 100644 tasks/01-Shell.md diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f87793701..000000000 --- a/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2014, Dmitriy Komanov -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/README.md b/README.md deleted file mode 100644 index 5040fedf1..000000000 --- a/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Программирование на языке JAVA - -Курс лекций и семинаров для студентов второго курса ФизТеха, факультет -[ФИВТ](http://fivt.fizteh.ru) на 2014 год. - -## Семинары -В папке [tasks](tasks) находятся описания заданий на -семинары. Для написания программ необходимо руководствоваться [соглашениями -по оформлению кода](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) -от Oracle (Code Conventions). - -В документе [github-workflow](github-workflow.md) описаны -общие правила по ведению задач на github, а также упрощение жизни с помощью утилиты -[checkstyle](http://checkstyle.sourceforge.net/), которая проверяет код на соответствие -Code Conventions. - -## Список литературы -* Брюс Эккель — Философия Java (Thinking in Java) -* Brian Goetz — Java Concurrency in Practive (продвинутая книжка -по многопоточности в Java) -* [Спецификации по JVM и JLS](http://docs.oracle.com/javase/specs/index.html) -* [Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) diff --git a/build.xml b/build.xml deleted file mode 100644 index 867e507fd..000000000 --- a/build.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/github-workflow.md b/github-workflow.md deleted file mode 100644 index e1ae4cab3..000000000 --- a/github-workflow.md +++ /dev/null @@ -1,16 +0,0 @@ -## Workflow работы с github - -Каждый студент делает [fork](https://help.github.com/articles/fork-a-repo) репозитория ```fizteh-java-2014```. Работа -ведётся в собственном репозитории, в директории ```src/ru/fizteh/fivt/students//```. - -После того, как задание выполнено и протестировано в собственном репозитории, необходимо создать -[pull request](https://help.github.com/articles/using-pull-requests) в репозиторий ```fizteh-java-2014```. В заголовке -к pull request необходимо написать: ```Имя Фамилия, № группы, задание``` (например, ```Василий Иванов, 123, Shell```). -Также необходимо назначить pull request на своего семинариста. - -В одном pull request должно быть решение только одной задачи. Если хочется сдавать параллельно несколько заданий, -необходимо создавать бранчи и делать pull request из бранчей. - -Чтобы сократить количество итераций на проверку задания, полезно самостоятельно удостовериться, что Code Conventions -соблюдены. Для этого нужно запустить сборку проекта с помощью ```ant checkstyle```. Вместо этого можно поставить -соответствующий плагин в IDE и настроить этот плагин на конфигурационный файл ```bin/checkstyle-rules.xml```. diff --git a/tasks/01-Calculator.md b/tasks/01-Calculator.md deleted file mode 100644 index d16049676..000000000 --- a/tasks/01-Calculator.md +++ /dev/null @@ -1,19 +0,0 @@ -## Калькулятор -Консольное приложение, на вход принимает выражение как параметр : -```bash -java Calculator "-(3 + 5.5) * 2 - 20/(15 - 5)" -``` - -Результат работы приложения -- результат выражения: -``` --19 -``` - -Поддерживаемые операции: ```+ - * /```. Приоритет операций -- математический -(скобки, потом унарное отрицание, потом умножение/деление, потом сложение/вычитание). - -В случае неправильных входных данных приложение должно вывести понятное описание -ошибки. - -Ограничения: не использовать встроенные скриптовые движки и кодо- или байткод генерацию. -Одним словом, парсить вручную. diff --git a/tasks/01-Shell.md b/tasks/01-Shell.md deleted file mode 100644 index a4c6dbda2..000000000 --- a/tasks/01-Shell.md +++ /dev/null @@ -1,113 +0,0 @@ -## Shell (Оболочка) -Консольное приложение, частично эмулирующее оболочку -[shell](http://en.wikipedia.org/wiki/Unix_shell). - -``` -java Shell [COMMAND1 [; COMMAND2 ...]] -``` - -Если Shell запускается без параметров, то запускается интерактивный режим, -в котором пользователь может ввести команду (или команды) прямо в консоли. - -Список команд: -* ```cd ``` — change directory, смена -текущей директории. Поддерживаются ```.```, ```..```, относительные и абсолютные -пути -* ```mkdir ``` — создание директории в текущей директории -* ```pwd``` — print working directory, печатает абсолютный путь к текущей -директории -* ```rm [-r] ``` — удаляет указанную в параметрах файл или папку. Если указать параметр ```-r``` то удаляется рекурсивно. -* ```cp [-r] ``` — копирует указанную в параметрах -папку/файл в указанное место. Параметр ```-r``` позволяет копировать рекурсивно. -* ```mv ``` — переносит указанный файл/папку в -новое место (файл на прежнем месте удаляется). В частности переименовывает -файл/папку, если ```source``` и ```destination``` находятся в одной папке -* ```ls``` — печатает содержимое текущей директории -* ```exit``` — выход из приложения -* ```cat ``` — выводит содержимое файла на экран. - -За один раз можно написать несколько команд. Разделителем команд является -```;``` (точка с запятой). - -### Интерактивный режим -В интерактивном режиме должно отображаться "приглашение" — ```$ ``` (знак -доллара и пробел), после которого производится ввод команд. Также в интерактивном -режиме допускается вывод текущей директории перед "приглашением". - -### Пакетный режим -Если запустить консольное приложение с параметрами, то параметры должны -интерпретироваться как команды (все команды должны склеиваться через пробел). -Приложение должно выполнить последовательно все команды и завершиться. - -В случае ошибки команды, приложение должно выводить ошибку в stderr. - -В случае ошибки в любой из команд, приложение должно написать сообщение об -ошибке и завершиться с ненулевым кодом. - -### Вывод команд -Вывод команд имеет строгий формат. Никакого дополнительного вывода в stdout быть -не должно (в финальном коде вся debug-информация должна отсутствовать). - -```(bash) -$ cd /noexistingdir -cd: '/noexistingdir': No such file or directory -$ cd /home/user -$ pwd -/home/user -$ ls -Folder -file.txt -$ mkdir MyFolder -$ ls -Folder -MyFolder -file.txt -$ cp file.txt MyFolder -$ cd MyFolder -$ ls -file.txt -$ mv file.txt file2.txt -$ ls -file2.txt -$ rm file.txt -rm: cannot remove 'file.txt': No such file or directory -$ rm file2.txt -$ ls -$ cd .. -$ ls -Folder -MyFolder -file.txt -$ mv Folder MyFolder -$ ls -MyFolder -file.txt -$ cp MyFolder NewFolder -cp: MyFolder is a directory (not copied). -$ ls -Folder -MyFolder -file.txt -$ cp -r MyFolder NewFolder -$ ls -Folder -MyFolder -NewFolder -file.txt -$ rm NewFolder -rm: NewFolder: is a directory -$ ls -Folder -MyFolder -NewFolder -file.txt -$ rm -r NewFolder -$ ls -Folder -MyFolder -file.txt -$ cat file.text -Hello World! -$ cat wrongfile.txt -cat: wrongfile.txt: No such file or directory -$ exit From 5d23a7da5b4eb57e016dfc7cbd6beaa20b7f80db Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 30 Sep 2014 16:18:48 +0400 Subject: [PATCH 09/30] added lib to the branch shell --- .gitignore | 1 + lib/checkstyle-rules.xml | 157 ++++++++++++++++++++++++++++++++++++ lib/checkstyle-suppress.xml | 7 ++ 3 files changed, 165 insertions(+) create mode 100644 lib/checkstyle-rules.xml create mode 100644 lib/checkstyle-suppress.xml diff --git a/.gitignore b/.gitignore index b84864001..5cf985168 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.DS_Store *.class # Mobile Tools for Java (J2ME) diff --git a/lib/checkstyle-rules.xml b/lib/checkstyle-rules.xml new file mode 100644 index 000000000..c73c18923 --- /dev/null +++ b/lib/checkstyle-rules.xml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/checkstyle-suppress.xml b/lib/checkstyle-suppress.xml new file mode 100644 index 000000000..2608395c6 --- /dev/null +++ b/lib/checkstyle-suppress.xml @@ -0,0 +1,7 @@ + + + + + + + From 54bfe2281e7d4d1edeeb9384ee8ebe101da02716 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 30 Sep 2014 18:48:19 +0400 Subject: [PATCH 10/30] modified lib in my branch to make checkstyle find suppress, added a lot of classes to implement behaviour of console utility --- lib/checkstyle-rules.xml | 2 +- .../students/Oktosha/Command/Command.java | 9 +++ .../ArgumentSyntaxException.java | 11 ++++ .../ConsoleUtility/CommandDoesNotExist.java | 10 ++++ .../ConsoleUtility/ConsoleUtility.java | 30 ++++++++++ .../ConsoleUtilityException.java | 10 ++++ .../students/Oktosha/Executor/Executor.java | 23 ++++++++ .../Oktosha/Executor/ExecutorException.java | 7 +++ .../Executor/ExecutorParseException.java | 7 +++ .../Oktosha/Executor/InteractiveExecutor.java | 16 ++++++ .../fivt/students/Oktosha/Shell/Shell.java | 56 ------------------- 11 files changed, 124 insertions(+), 57 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Command/Command.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorException.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorParseException.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java diff --git a/lib/checkstyle-rules.xml b/lib/checkstyle-rules.xml index c73c18923..77cc1e3d6 100644 --- a/lib/checkstyle-rules.xml +++ b/lib/checkstyle-rules.xml @@ -5,7 +5,7 @@ - + diff --git a/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java b/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java new file mode 100644 index 000000000..2d95942e1 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java @@ -0,0 +1,9 @@ +package ru.fizteh.fivt.students.Oktosha.Command; + +/** + * A simple class which holds name of command and it's arguments. + */ +public class Command { + public String name; + public String[] args; +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java new file mode 100644 index 000000000..bb3135358 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java @@ -0,0 +1,11 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * The exception which is thrown when there is a syntax error in arguments + * given to command of ConsoleUtility. + */ +public class ArgumentSyntaxException extends ConsoleUtilityException { + ArgumentSyntaxException(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java new file mode 100644 index 000000000..9f74d57ff --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java @@ -0,0 +1,10 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * Created by DKolodzey on 30.09.14. + */ +public class CommandDoesNotExist extends ConsoleUtilityException { + CommandDoesNotExist(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java new file mode 100644 index 000000000..1a4d2b7c0 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java @@ -0,0 +1,30 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +import ru.fizteh.fivt.students.Oktosha.Command.Command; + +/** + * ConsoleUtility is a class which should be extended by Shell, DbMain or + * whatever else which represents a set of console commands. + */ +public abstract class ConsoleUtility { + + public void run(Command cmd) throws CommandDoesNotExist, + ArgumentSyntaxException { + switch (cmd.name) { + case "exit": + exit(cmd.args); + break; + case "": + break; + default: + throw new CommandDoesNotExist(cmd.name + ": doesn't exist"); + } + } + + protected void exit(String[] args) throws ArgumentSyntaxException { + if (args.length != 0) { + throw new ArgumentSyntaxException("exit: too many arguments"); + } + System.exit(0); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java new file mode 100644 index 000000000..0064f6224 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java @@ -0,0 +1,10 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * Parent class for all exceptions thrown by ConsoleUtility + */ +public class ConsoleUtilityException extends Exception { + ConsoleUtilityException(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java new file mode 100644 index 000000000..32df959a3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java @@ -0,0 +1,23 @@ +package ru.fizteh.fivt.students.Oktosha.Executor; + +import ru.fizteh.fivt.students.Oktosha.Command.Command; + + +/** + * A class which executes an instance of ConsoleUtility + */ +public abstract class Executor { + protected Command[] parse(String s) throws ExecutorParseException { + if (s.matches(".*;\\s*;.*")) { + throw new ExecutorParseException(); + } + String[] commandStrings = s.split(";"); + Command[] res = new Command[commandStrings.length]; + for (int i = 0; i < res.length; ++i) { + String[] split = commandStrings[i].split("\\s+"); + res[i].name = split[0]; + System.arraycopy(split, 1, res[i].args, 0, split.length - 1); + } + return res; + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorException.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorException.java new file mode 100644 index 000000000..7e391e281 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorException.java @@ -0,0 +1,7 @@ +package ru.fizteh.fivt.students.Oktosha.Executor; + +/** + * Parent class for all exceptions thrown by executor. + */ +public class ExecutorException extends Exception { +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorParseException.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorParseException.java new file mode 100644 index 000000000..7e16917ae --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/ExecutorParseException.java @@ -0,0 +1,7 @@ +package ru.fizteh.fivt.students.Oktosha.Executor; + +/** + * This exception is thrown when parsed command is empty + */ +public class ExecutorParseException extends ExecutorException { +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java new file mode 100644 index 000000000..e5ca4720d --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java @@ -0,0 +1,16 @@ +package ru.fizteh.fivt.students.Oktosha.Executor; + +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; + +import java.io.Console; + +/** + * InteractiveExecutor is a child of Executor + * which runs ConsoleUtility in interactive mode + */ +public class InteractiveExecutor { + public void execute(ConsoleUtility utility) { + Console c = System.console(); + String commands = c.readLine("$ "); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 73c00ab46..360eb11f1 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -12,63 +12,7 @@ public final class Shell { /** * In this class params to run command are stored. */ - class Command { - /** - * Constructor - * - * @param cmdVal will be assigned to cmd - * @param argsVal will be assigned to args - */ - public Command(final String cmdVal, final String[] argsVal) { - cmd = cmdVal; - args = argsVal; - } - - /** - * Cmd setter. - * - * @param str the value to set to cmd - */ - public void setCmd(final String str) { - cmd = str; - } - - /** - * Args setter. - * - * @param strArray the value to set to args - */ - public void setArgs(final String[] strArray) { - args = strArray; - } - /** - * Cmd getter. - * - * @return actual value of cmd - */ - public String getCmd() { - return cmd; - } - - /** - * Args getter. - * - * @return actual value of args - */ - public String[] getArgs() { - return args; - } - - /** - * The name of command is stored in cmd. - */ - private String cmd; - /** - * The arguments passed to command are stored in args. - */ - private String[] args; - } /** * @param args command line arguments are treated as shell commands From aaf7b57161b5c0ab333a96b1cbf98556b1c606ca Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 30 Sep 2014 20:03:23 +0400 Subject: [PATCH 11/30] added implementations of executor, need debug --- .../ArgumentSyntaxException.java | 2 +- .../ConsoleUtility/CommandDoesNotExist.java | 2 +- .../ConsoleUtility/ConsoleUtility.java | 27 +----- .../students/Oktosha/Executor/Executor.java | 7 +- .../Oktosha/Executor/InteractiveExecutor.java | 26 ++++- .../Oktosha/Executor/PackageExecutor.java | 29 ++++++ .../fivt/students/Oktosha/Shell/Shell.java | 95 +++++-------------- 7 files changed, 85 insertions(+), 103 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java index bb3135358..a5b467aab 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java @@ -5,7 +5,7 @@ * given to command of ConsoleUtility. */ public class ArgumentSyntaxException extends ConsoleUtilityException { - ArgumentSyntaxException(String s) { + public ArgumentSyntaxException(String s) { super(s); } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java index 9f74d57ff..4a28d6083 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java @@ -4,7 +4,7 @@ * Created by DKolodzey on 30.09.14. */ public class CommandDoesNotExist extends ConsoleUtilityException { - CommandDoesNotExist(String s) { + public CommandDoesNotExist(String s) { super(s); } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java index 1a4d2b7c0..293d468b6 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java @@ -3,28 +3,9 @@ import ru.fizteh.fivt.students.Oktosha.Command.Command; /** - * ConsoleUtility is a class which should be extended by Shell, DbMain or - * whatever else which represents a set of console commands. + * ConsoleUtility is an interface which should be implemented by Shell, + * DbMain or whatever else ConsoleUtility run by Executor. */ -public abstract class ConsoleUtility { - - public void run(Command cmd) throws CommandDoesNotExist, - ArgumentSyntaxException { - switch (cmd.name) { - case "exit": - exit(cmd.args); - break; - case "": - break; - default: - throw new CommandDoesNotExist(cmd.name + ": doesn't exist"); - } - } - - protected void exit(String[] args) throws ArgumentSyntaxException { - if (args.length != 0) { - throw new ArgumentSyntaxException("exit: too many arguments"); - } - System.exit(0); - } +public interface ConsoleUtility { + void run(Command cmd) throws CommandDoesNotExist, ArgumentSyntaxException; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java index 32df959a3..533d3a60d 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java @@ -2,12 +2,15 @@ import ru.fizteh.fivt.students.Oktosha.Command.Command; - /** * A class which executes an instance of ConsoleUtility */ public abstract class Executor { - protected Command[] parse(String s) throws ExecutorParseException { + + static final int SYNTAX_ERROR = 1; + static final int COMMAND_RUNTIME_ERROR = 2; + + protected static Command[] parse(String s) throws ExecutorParseException { if (s.matches(".*;\\s*;.*")) { throw new ExecutorParseException(); } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java index e5ca4720d..989df79e4 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java @@ -1,16 +1,32 @@ package ru.fizteh.fivt.students.Oktosha.Executor; +import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilityException; -import java.io.Console; +import java.util.Scanner; /** * InteractiveExecutor is a child of Executor * which runs ConsoleUtility in interactive mode */ -public class InteractiveExecutor { - public void execute(ConsoleUtility utility) { - Console c = System.console(); - String commands = c.readLine("$ "); +public class InteractiveExecutor extends Executor { + public static void execute(ConsoleUtility utility) { + Scanner sc = new Scanner(System.in); + for (; ; ) { + System.out.print("$ "); + String commandsString = sc.nextLine(); + try { + Command[] commands = parse(commandsString); + for (Command cmd : commands) { + utility.run(cmd); + } + } catch (ExecutorParseException e) { + System.err.println("invalid syntax: empty command between two semicolons"); + } catch (ConsoleUtilityException e) { + System.err.println(e.getMessage()); + } + + } } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java new file mode 100644 index 000000000..9c2965e0e --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java @@ -0,0 +1,29 @@ +package ru.fizteh.fivt.students.Oktosha.Executor; + +import ru.fizteh.fivt.students.Oktosha.Command.Command; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilityException; + +/** + * Class which runs console utility in package mode + */ +public class PackageExecutor extends Executor { + public static void execute(ConsoleUtility utility, String[] args) { + String commandsString = ""; + for (String str : args) { + commandsString.concat(" " + str); + } + try { + Command[] commands = parse(commandsString); + for (Command cmd : commands) { + utility.run(cmd); + } + } catch (ExecutorParseException e) { + System.err.println("invalid syntax: empty command between two semicolons"); + System.exit(Executor.SYNTAX_ERROR); + } catch (ConsoleUtilityException e) { + System.err.println(e.getMessage()); + System.exit(Executor.SYNTAX_ERROR); + } + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 360eb11f1..bdb457a62 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,86 +1,39 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +import ru.fizteh.fivt.students.Oktosha.Command.Command; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ArgumentSyntaxException; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandDoesNotExist; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; +import ru.fizteh.fivt.students.Oktosha.Executor.InteractiveExecutor; +import ru.fizteh.fivt.students.Oktosha.Executor.PackageExecutor; -import java.nio.file.Path; -import java.nio.file.Paths; +public class Shell implements ConsoleUtility { -/** - * The Shell class implements an application, - * which partially emulates UNIX command line. - */ -public final class Shell { - /** - * In this class params to run command are stored. - */ - - - /** - * @param args command line arguments are treated as shell commands - * if no arguments are given Shell runs in interactive mode - */ - public static void main(final String[] args) { - workingDirectory = Paths.get("."); + public static void main(String[] args) { if (args.length == 0) { - interactiveMode(); + InteractiveExecutor.execute(new Shell()); } else { - packageMode(args); + PackageExecutor.execute(new Shell(), args); } } - /** - * The method which implements interactive mode of Shell. - */ - private static void interactiveMode() { - System.out.print("$"); - } - - /** - * The method which implements package mode of Shell. - * - * @param args are command line arguments which are treated as commands - */ - private static void packageMode(final String[] args) { - System.out.println("package"); - String commandString = ""; - for (String s : args) { - commandString = commandString.concat(" "); - commandString = commandString.concat(s); - System.out.println(s); + public void run(Command cmd) throws CommandDoesNotExist, + ArgumentSyntaxException { + switch (cmd.name) { + case "exit": + exit(cmd.args); + break; + case "": + break; + default: + throw new CommandDoesNotExist(cmd.name + ": doesn't exist"); } - System.out.print(commandString); - } - - /** - * Command pwd prints current working directory. - */ - private static void pwd() { - System.out.println(workingDirectory.toAbsolutePath().normalize()); } - /** - * a method which parses string with commands and returns array of Command. - * - * @param str contains commands which the user entered. - * @return array of commands. - */ - /* private Command[] parseCommandString(final String str) { - String[] splitBySemicolon = str.split(";"); - Command[] ans = new Command[splitBySemicolon.length]; - for (String cmd : splitBySemicolon) { - String[] cmdParsed = cmd.split("\\s"); - + protected void exit(String[] args) throws ArgumentSyntaxException { + if (args.length != 0) { + throw new ArgumentSyntaxException("exit: too many arguments"); } - }*/ - - /** - * A variable holding current working directory. - */ - private static Path workingDirectory; - - /** - * This is a private constructor, which is never called. - */ - private Shell() { + System.exit(0); } } - From adb4f3067f1e4b13986c1e31e50d17293b1213b7 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 1 Oct 2014 00:26:14 +0400 Subject: [PATCH 12/30] wrote something really working, just need to add more commands --- .../fizteh/fivt/students/Oktosha/Command/Command.java | 7 +++++++ .../Oktosha/ConsoleUtility/CommandDoesNotExist.java | 10 ---------- .../ConsoleUtility/CommandIsNotSupportedException.java | 10 ++++++++++ .../Oktosha/ConsoleUtility/ConsoleUtility.java | 2 +- .../fivt/students/Oktosha/Executor/Executor.java | 4 +--- .../students/Oktosha/Executor/PackageExecutor.java | 6 ++++-- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 10 +++++----- 7 files changed, 28 insertions(+), 21 deletions(-) delete mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java b/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java index 2d95942e1..0a2b9882f 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Command/Command.java @@ -4,6 +4,13 @@ * A simple class which holds name of command and it's arguments. */ public class Command { + public Command(String commandString) { + commandString = commandString.trim(); + String[] split = commandString.split("\\s+"); + name = split[0]; + args = new String[split.length - 1]; + System.arraycopy(split, 1, args, 0, split.length - 1); + } public String name; public String[] args; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java deleted file mode 100644 index 4a28d6083..000000000 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandDoesNotExist.java +++ /dev/null @@ -1,10 +0,0 @@ -package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; - -/** - * Created by DKolodzey on 30.09.14. - */ -public class CommandDoesNotExist extends ConsoleUtilityException { - public CommandDoesNotExist(String s) { - super(s); - } -} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java new file mode 100644 index 000000000..65c3ca8dd --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java @@ -0,0 +1,10 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * Created by DKolodzey on 30.09.14. + */ +public class CommandIsNotSupportedException extends ConsoleUtilityException { + public CommandIsNotSupportedException(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java index 293d468b6..db5a47447 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java @@ -7,5 +7,5 @@ * DbMain or whatever else ConsoleUtility run by Executor. */ public interface ConsoleUtility { - void run(Command cmd) throws CommandDoesNotExist, ArgumentSyntaxException; + void run(Command cmd) throws CommandIsNotSupportedException, ArgumentSyntaxException; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java index 533d3a60d..2acf9bded 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java @@ -17,9 +17,7 @@ protected static Command[] parse(String s) throws ExecutorParseException { String[] commandStrings = s.split(";"); Command[] res = new Command[commandStrings.length]; for (int i = 0; i < res.length; ++i) { - String[] split = commandStrings[i].split("\\s+"); - res[i].name = split[0]; - System.arraycopy(split, 1, res[i].args, 0, split.length - 1); + res[i] = new Command(commandStrings[i]); } return res; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java index 9c2965e0e..2115cc3ab 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java @@ -9,10 +9,12 @@ */ public class PackageExecutor extends Executor { public static void execute(ConsoleUtility utility, String[] args) { - String commandsString = ""; + StringBuilder builder = new StringBuilder(); for (String str : args) { - commandsString.concat(" " + str); + builder.append(" "); + builder.append(str); } + String commandsString = builder.toString(); try { Command[] commands = parse(commandsString); for (Command cmd : commands) { diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index bdb457a62..a313d0567 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -2,7 +2,7 @@ import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ArgumentSyntaxException; -import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandDoesNotExist; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandIsNotSupportedException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; import ru.fizteh.fivt.students.Oktosha.Executor.InteractiveExecutor; import ru.fizteh.fivt.students.Oktosha.Executor.PackageExecutor; @@ -17,8 +17,8 @@ public static void main(String[] args) { } } - public void run(Command cmd) throws CommandDoesNotExist, - ArgumentSyntaxException { + public void run(Command cmd) throws CommandIsNotSupportedException, + ArgumentSyntaxException { switch (cmd.name) { case "exit": exit(cmd.args); @@ -26,11 +26,11 @@ public void run(Command cmd) throws CommandDoesNotExist, case "": break; default: - throw new CommandDoesNotExist(cmd.name + ": doesn't exist"); + throw new CommandIsNotSupportedException(cmd.name + ": command isn't supported"); } } - protected void exit(String[] args) throws ArgumentSyntaxException { + private void exit(String[] args) throws ArgumentSyntaxException { if (args.length != 0) { throw new ArgumentSyntaxException("exit: too many arguments"); } From ab6fdd3c34e94cd3d63fd02b7e5663ff6bb50e32 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Thu, 2 Oct 2014 23:04:04 +0400 Subject: [PATCH 13/30] added pwd --- .../Oktosha/Executor/InteractiveExecutor.java | 11 +++++++++-- .../fivt/students/Oktosha/Shell/Shell.java | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java index 989df79e4..f10d81b7b 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java @@ -13,8 +13,9 @@ public class InteractiveExecutor extends Executor { public static void execute(ConsoleUtility utility) { Scanner sc = new Scanner(System.in); + System.out.print("$ "); + System.out.flush(); for (; ; ) { - System.out.print("$ "); String commandsString = sc.nextLine(); try { Command[] commands = parse(commandsString); @@ -23,10 +24,16 @@ public static void execute(ConsoleUtility utility) { } } catch (ExecutorParseException e) { System.err.println("invalid syntax: empty command between two semicolons"); + System.err.flush(); } catch (ConsoleUtilityException e) { System.err.println(e.getMessage()); + System.err.flush(); + System.out.flush(); + } finally { + System.out.print("$ "); + System.out.flush(); + System.err.flush(); } - } } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index a313d0567..4d0dc0778 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,5 +1,8 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +import java.nio.file.Path; +import java.nio.file.Paths; + import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ArgumentSyntaxException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandIsNotSupportedException; @@ -9,6 +12,12 @@ public class Shell implements ConsoleUtility { + private Path workingDirectory; + + Shell() { + workingDirectory = Paths.get(System.getProperty("user.dir")); + } + public static void main(String[] args) { if (args.length == 0) { InteractiveExecutor.execute(new Shell()); @@ -23,6 +32,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "exit": exit(cmd.args); break; + case "pwd": + pwd(cmd.args); + break; case "": break; default: @@ -36,4 +48,11 @@ private void exit(String[] args) throws ArgumentSyntaxException { } System.exit(0); } + + private void pwd(String[] args) throws ArgumentSyntaxException { + if (args.length != 0) { + throw new ArgumentSyntaxException("pwd: too many arguments"); + } + System.out.println(workingDirectory); + } } From cc20268a8f139e54ebce431ccef7e5228d96b1b2 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Fri, 3 Oct 2014 01:42:58 +0400 Subject: [PATCH 14/30] restored checkstyle-rules.xml --- build.xml | 60 ++++++++++++++++++++++++++++++++++++++++ lib/checkstyle-rules.xml | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 build.xml diff --git a/build.xml b/build.xml new file mode 100644 index 000000000..f5898b1a7 --- /dev/null +++ b/build.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/checkstyle-rules.xml b/lib/checkstyle-rules.xml index 77cc1e3d6..c73c18923 100644 --- a/lib/checkstyle-rules.xml +++ b/lib/checkstyle-rules.xml @@ -5,7 +5,7 @@ - + From 97db5ec9b84564a30b4008bd7e7b519d7b136820 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Fri, 3 Oct 2014 02:06:14 +0400 Subject: [PATCH 15/30] improved ConsoleUtility exceptions --- ...tion.java => CommandArgumentSyntaxException.java} | 4 ++-- .../CommandIsNotSupportedException.java | 2 +- .../Oktosha/ConsoleUtility/ConsoleUtility.java | 3 ++- .../ConsoleUtilityRuntimeException.java | 10 ++++++++++ .../ConsoleUtilitySyntaxException.java | 12 ++++++++++++ .../students/Oktosha/Executor/PackageExecutor.java | 4 ++-- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 12 ++++++------ 7 files changed, 35 insertions(+), 12 deletions(-) rename src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/{ArgumentSyntaxException.java => CommandArgumentSyntaxException.java} (59%) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java create mode 100644 src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilitySyntaxException.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandArgumentSyntaxException.java similarity index 59% rename from src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java rename to src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandArgumentSyntaxException.java index a5b467aab..810100cf1 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ArgumentSyntaxException.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandArgumentSyntaxException.java @@ -4,8 +4,8 @@ * The exception which is thrown when there is a syntax error in arguments * given to command of ConsoleUtility. */ -public class ArgumentSyntaxException extends ConsoleUtilityException { - public ArgumentSyntaxException(String s) { +public class CommandArgumentSyntaxException extends ConsoleUtilitySyntaxException { + public CommandArgumentSyntaxException(String s) { super(s); } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java index 65c3ca8dd..a69f807bf 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/CommandIsNotSupportedException.java @@ -3,7 +3,7 @@ /** * Created by DKolodzey on 30.09.14. */ -public class CommandIsNotSupportedException extends ConsoleUtilityException { +public class CommandIsNotSupportedException extends ConsoleUtilitySyntaxException { public CommandIsNotSupportedException(String s) { super(s); } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java index db5a47447..b94d12288 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java @@ -7,5 +7,6 @@ * DbMain or whatever else ConsoleUtility run by Executor. */ public interface ConsoleUtility { - void run(Command cmd) throws CommandIsNotSupportedException, ArgumentSyntaxException; + void run(Command cmd) throws CommandIsNotSupportedException, + CommandArgumentSyntaxException; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java new file mode 100644 index 000000000..322436503 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java @@ -0,0 +1,10 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * This exception is thrown when an error during running command occurs. + */ +public class ConsoleUtilityRuntimeException extends ConsoleUtilityException { + public ConsoleUtilityRuntimeException(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilitySyntaxException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilitySyntaxException.java new file mode 100644 index 000000000..aa9d52384 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilitySyntaxException.java @@ -0,0 +1,12 @@ +package ru.fizteh.fivt.students.Oktosha.ConsoleUtility; + +/** + * Child class of ConsoleUtilityException. + * It is thrown when command has invalid syntax. + */ + +public class ConsoleUtilitySyntaxException extends ConsoleUtilityException { + ConsoleUtilitySyntaxException(String s) { + super(s); + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java index 2115cc3ab..401d55774 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java @@ -2,7 +2,7 @@ import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; -import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilityException; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilitySyntaxException; /** * Class which runs console utility in package mode @@ -23,7 +23,7 @@ public static void execute(ConsoleUtility utility, String[] args) { } catch (ExecutorParseException e) { System.err.println("invalid syntax: empty command between two semicolons"); System.exit(Executor.SYNTAX_ERROR); - } catch (ConsoleUtilityException e) { + } catch (ConsoleUtilitySyntaxException e) { System.err.println(e.getMessage()); System.exit(Executor.SYNTAX_ERROR); } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 4d0dc0778..8afb0d78c 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -4,7 +4,7 @@ import java.nio.file.Paths; import ru.fizteh.fivt.students.Oktosha.Command.Command; -import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ArgumentSyntaxException; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandArgumentSyntaxException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandIsNotSupportedException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; import ru.fizteh.fivt.students.Oktosha.Executor.InteractiveExecutor; @@ -27,7 +27,7 @@ public static void main(String[] args) { } public void run(Command cmd) throws CommandIsNotSupportedException, - ArgumentSyntaxException { + CommandArgumentSyntaxException { switch (cmd.name) { case "exit": exit(cmd.args); @@ -42,16 +42,16 @@ public void run(Command cmd) throws CommandIsNotSupportedException, } } - private void exit(String[] args) throws ArgumentSyntaxException { + private void exit(String[] args) throws CommandArgumentSyntaxException { if (args.length != 0) { - throw new ArgumentSyntaxException("exit: too many arguments"); + throw new CommandArgumentSyntaxException("exit: too many arguments"); } System.exit(0); } - private void pwd(String[] args) throws ArgumentSyntaxException { + private void pwd(String[] args) throws CommandArgumentSyntaxException { if (args.length != 0) { - throw new ArgumentSyntaxException("pwd: too many arguments"); + throw new CommandArgumentSyntaxException("pwd: too many arguments"); } System.out.println(workingDirectory); } From c89d6444ecfd774e71a95e68fa5d00de195c8f11 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Fri, 3 Oct 2014 02:51:15 +0400 Subject: [PATCH 16/30] added cd --- .../ConsoleUtility/ConsoleUtility.java | 3 +- .../ConsoleUtilityException.java | 5 +++- .../ConsoleUtilityRuntimeException.java | 3 ++ .../Oktosha/Executor/PackageExecutor.java | 4 +++ .../fivt/students/Oktosha/Shell/Shell.java | 30 ++++++++++++++++++- 5 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java index b94d12288..ccdb38ef5 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtility.java @@ -8,5 +8,6 @@ */ public interface ConsoleUtility { void run(Command cmd) throws CommandIsNotSupportedException, - CommandArgumentSyntaxException; + CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException; } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java index 0064f6224..7d77db79e 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityException.java @@ -4,7 +4,10 @@ * Parent class for all exceptions thrown by ConsoleUtility */ public class ConsoleUtilityException extends Exception { - ConsoleUtilityException(String s) { + public ConsoleUtilityException(String s) { super(s); } + public ConsoleUtilityException(String s, Exception e) { + super(s, e); + } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java index 322436503..bf01e0c54 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java +++ b/src/ru/fizteh/fivt/students/Oktosha/ConsoleUtility/ConsoleUtilityRuntimeException.java @@ -7,4 +7,7 @@ public class ConsoleUtilityRuntimeException extends ConsoleUtilityException { public ConsoleUtilityRuntimeException(String s) { super(s); } + public ConsoleUtilityRuntimeException(String s, Exception e) { + super(s, e); + } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java index 401d55774..af6c1b73b 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java @@ -2,6 +2,7 @@ import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilityRuntimeException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilitySyntaxException; /** @@ -26,6 +27,9 @@ public static void execute(ConsoleUtility utility, String[] args) { } catch (ConsoleUtilitySyntaxException e) { System.err.println(e.getMessage()); System.exit(Executor.SYNTAX_ERROR); + } catch (ConsoleUtilityRuntimeException e) { + System.err.println(e.getMessage()); + System.exit(Executor.COMMAND_RUNTIME_ERROR); } } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 8afb0d78c..72cf75cec 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,12 +1,16 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +import java.io.IOException; +import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.Files; import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandArgumentSyntaxException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandIsNotSupportedException; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtility; +import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.ConsoleUtilityRuntimeException; import ru.fizteh.fivt.students.Oktosha.Executor.InteractiveExecutor; import ru.fizteh.fivt.students.Oktosha.Executor.PackageExecutor; @@ -27,8 +31,12 @@ public static void main(String[] args) { } public void run(Command cmd) throws CommandIsNotSupportedException, - CommandArgumentSyntaxException { + CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException { switch (cmd.name) { + case "cd": + cd(cmd.args); + break; case "exit": exit(cmd.args); break; @@ -55,4 +63,24 @@ private void pwd(String[] args) throws CommandArgumentSyntaxException { } System.out.println(workingDirectory); } + + private void cd(String[] args) throws CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException { + if (args.length != 1) { + throw new CommandArgumentSyntaxException("cd: expected 1 argument, found " + args.length); + } + try { + Path destinationPath = Paths.get(args[0]); + Path newWorkingDirectory = workingDirectory.resolve(destinationPath); + newWorkingDirectory = newWorkingDirectory.toRealPath(); + if (!Files.isDirectory(newWorkingDirectory)) { + throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': Not a directory"); + } + workingDirectory = newWorkingDirectory; + } catch (InvalidPathException e) { + throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': Invalid path", e); + } catch (IOException e) { + throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': No such file or directory", e); + } + } } From d0f1e462f9fa0e7260de646c05b64eb46cb2c99b Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 00:58:29 +0400 Subject: [PATCH 17/30] wrote mkdir --- .../fivt/students/Oktosha/Shell/Shell.java | 59 +++++++++++++------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 72cf75cec..c9dd490b2 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,10 +1,7 @@ package ru.fizteh.fivt.students.Oktosha.Shell; import java.io.IOException; -import java.nio.file.InvalidPathException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.Files; +import java.nio.file.*; import ru.fizteh.fivt.students.Oktosha.Command.Command; import ru.fizteh.fivt.students.Oktosha.ConsoleUtility.CommandArgumentSyntaxException; @@ -40,6 +37,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "exit": exit(cmd.args); break; + case "mkdir": + mkdir(cmd.args); + break; case "pwd": pwd(cmd.args); break; @@ -50,22 +50,8 @@ public void run(Command cmd) throws CommandIsNotSupportedException, } } - private void exit(String[] args) throws CommandArgumentSyntaxException { - if (args.length != 0) { - throw new CommandArgumentSyntaxException("exit: too many arguments"); - } - System.exit(0); - } - - private void pwd(String[] args) throws CommandArgumentSyntaxException { - if (args.length != 0) { - throw new CommandArgumentSyntaxException("pwd: too many arguments"); - } - System.out.println(workingDirectory); - } - private void cd(String[] args) throws CommandArgumentSyntaxException, - ConsoleUtilityRuntimeException { + ConsoleUtilityRuntimeException { if (args.length != 1) { throw new CommandArgumentSyntaxException("cd: expected 1 argument, found " + args.length); } @@ -83,4 +69,39 @@ private void cd(String[] args) throws CommandArgumentSyntaxException, throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': No such file or directory", e); } } + + private void exit(String[] args) throws CommandArgumentSyntaxException { + if (args.length != 0) { + throw new CommandArgumentSyntaxException("exit: too many arguments"); + } + System.exit(0); + } + + private void mkdir(String[] args) throws CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException { + if (args.length != 1) { + throw new CommandArgumentSyntaxException("mkdir: expected 1 argument, found " + args.length); + } + Path newDirectoryPath = workingDirectory.resolve(Paths.get(args[0])); + try { + Files.createDirectory(newDirectoryPath); + } catch (FileAlreadyExistsException e) { + throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] + ": File exists", e); + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] + ": Permission denied", e); + } catch (NoSuchFileException e) { + throw new ConsoleUtilityRuntimeException("mkdir: " + + Paths.get(args[0]).getParent() + + ": No such file or directory", e); + } catch (IOException | SecurityException e) { + throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] + ": something really bad happened", e); + } + } + + private void pwd(String[] args) throws CommandArgumentSyntaxException { + if (args.length != 0) { + throw new CommandArgumentSyntaxException("pwd: too many arguments"); + } + System.out.println(workingDirectory); + } } From 3aab9712dbfa037b278fe3b57dad7dd4a3ef22b0 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 01:52:54 +0400 Subject: [PATCH 18/30] added ls, improved exceptions in cd --- .../fivt/students/Oktosha/Shell/Shell.java | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index c9dd490b2..6f24c85e6 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -37,6 +37,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "exit": exit(cmd.args); break; + case "ls": + ls(cmd.args); + break; case "mkdir": mkdir(cmd.args); break; @@ -63,10 +66,12 @@ private void cd(String[] args) throws CommandArgumentSyntaxException, throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': Not a directory"); } workingDirectory = newWorkingDirectory; - } catch (InvalidPathException e) { - throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': Invalid path", e); - } catch (IOException e) { + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': Permission denied", e); + } catch (NoSuchFileException | InvalidPathException e) { throw new ConsoleUtilityRuntimeException("cd: '" + args[0] + "': No such file or directory", e); + } catch (IOException e) { + throw new ConsoleUtilityRuntimeException("cd: something really bad happened " + e.toString(), e); } } @@ -77,6 +82,24 @@ private void exit(String[] args) throws CommandArgumentSyntaxException { System.exit(0); } + private void ls(String[] args) throws CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException { + if (args.length != 0) { + throw new CommandArgumentSyntaxException("ls: too many arguments"); + } + try (DirectoryStream stream = Files.newDirectoryStream(workingDirectory)) { + for (Path file : stream) { + System.out.println(file.getFileName()); + } + } catch (NoSuchFileException e) { + throw new ConsoleUtilityRuntimeException("ls: Working directory doesn't exist", e); + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("ls: Permission denied", e); + } catch (IOException | DirectoryIteratorException e) { + throw new ConsoleUtilityRuntimeException("ls: something really bad happened " + e.toString(), e); + } + } + private void mkdir(String[] args) throws CommandArgumentSyntaxException, ConsoleUtilityRuntimeException { if (args.length != 1) { @@ -94,7 +117,9 @@ private void mkdir(String[] args) throws CommandArgumentSyntaxException, + Paths.get(args[0]).getParent() + ": No such file or directory", e); } catch (IOException | SecurityException e) { - throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] + ": something really bad happened", e); + throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] + + ": something really bad happened " + + e.toString(), e); } } From aab547b299331394243bfb8e1091e72e86c8bf00 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 02:33:34 +0400 Subject: [PATCH 19/30] added cat --- .../fivt/students/Oktosha/Shell/Shell.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 6f24c85e6..5c24ccad4 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,5 +1,6 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +import java.io.BufferedReader; import java.io.IOException; import java.nio.file.*; @@ -31,6 +32,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, CommandArgumentSyntaxException, ConsoleUtilityRuntimeException { switch (cmd.name) { + case "cat": + cat(cmd.args); + break; case "cd": cd(cmd.args); break; @@ -53,8 +57,30 @@ public void run(Command cmd) throws CommandIsNotSupportedException, } } + private void cat(String[] args) throws CommandArgumentSyntaxException, + ConsoleUtilityRuntimeException { + if (args.length != 1) { + throw new CommandArgumentSyntaxException("cat: expected 1 argument, found " + args.length); + } + try { + Path filePath = workingDirectory.resolve(Paths.get(args[0])).toRealPath(); + try (BufferedReader reader = Files.newBufferedReader(filePath)) { + String line = null; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("cat: '" + args[0] + "': Permission denied", e); + } catch (IOException e) { + throw new ConsoleUtilityRuntimeException("cat: something really bad happened " + e.toString(), e); + } + } catch (IOException e) { + throw new ConsoleUtilityRuntimeException("cat: " + args[0] + "': No such file or directory", e); + } + } + private void cd(String[] args) throws CommandArgumentSyntaxException, - ConsoleUtilityRuntimeException { + ConsoleUtilityRuntimeException { if (args.length != 1) { throw new CommandArgumentSyntaxException("cd: expected 1 argument, found " + args.length); } From 1c2b1e51e56d2b7eddfbefdb42a69e10cc7c4451 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 13:27:16 +0400 Subject: [PATCH 20/30] wrote mv --- .../fivt/students/Oktosha/Shell/Shell.java | 50 +++++++++++++++++-- .../students/Oktosha/Shell/mvFileVisitor.java | 40 +++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 5c24ccad4..af086a723 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -1,5 +1,6 @@ package ru.fizteh.fivt.students.Oktosha.Shell; +import static java.nio.file.StandardCopyOption.*; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.*; @@ -47,6 +48,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "mkdir": mkdir(cmd.args); break; + case "mv": + mv(cmd.args); + break; case "pwd": pwd(cmd.args); break; @@ -65,7 +69,7 @@ private void cat(String[] args) throws CommandArgumentSyntaxException, try { Path filePath = workingDirectory.resolve(Paths.get(args[0])).toRealPath(); try (BufferedReader reader = Files.newBufferedReader(filePath)) { - String line = null; + String line; while ((line = reader.readLine()) != null) { System.out.println(line); } @@ -143,9 +147,47 @@ private void mkdir(String[] args) throws CommandArgumentSyntaxException, + Paths.get(args[0]).getParent() + ": No such file or directory", e); } catch (IOException | SecurityException e) { - throw new ConsoleUtilityRuntimeException("mkdir: " + args[0] - + ": something really bad happened " - + e.toString(), e); + throw new ConsoleUtilityRuntimeException("mkdir: something really bad happened " + e.toString(), e); + } + } + + private void mv(String[] args) throws CommandArgumentSyntaxException, ConsoleUtilityRuntimeException { + if (args.length != 2) { + throw new CommandArgumentSyntaxException("mv: expected 2 arguments, found " + args.length); + } + try { + Path source = workingDirectory.resolve(Paths.get(args[0])).toRealPath(); + Path target = workingDirectory.resolve(Paths.get(args[1])); + + if (Files.exists(target) && source.equals(target.toRealPath())) { + return; + } + + if (Files.isDirectory(source)) { + if (Files.exists(target)) { + if (Files.isDirectory(target)) { + Files.walkFileTree(source, new MvFileVisitor(source, target.resolve(source.getFileName()))); + } else { + throw new ConsoleUtilityRuntimeException("mv: rename '" + + args[0] + "' to '" + args[1] + + ": Not a directory"); + } + } else { + Files.walkFileTree(source, new MvFileVisitor(source, target)); + } + } else { + if (Files.exists(target) && Files.isDirectory(target)) { + Files.move(source, target.resolve(source.getFileName()), REPLACE_EXISTING); + } else { + Files.move(source, target, REPLACE_EXISTING); + } + } + } catch (NoSuchFileException e) { + throw new ConsoleUtilityRuntimeException("mv: " + e.getMessage() + ": No such file or directory", e); + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("mkdir: " + e.getMessage() + ": Permission denied", e); + } catch (IOException | SecurityException e) { + throw new ConsoleUtilityRuntimeException("mv: something really bad happened " + e.toString(), e); } } diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java new file mode 100644 index 000000000..e0790150f --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java @@ -0,0 +1,40 @@ +package ru.fizteh.fivt.students.Oktosha.Shell; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + +/** + * Class which moves a directory recursively + */ + +public class MvFileVisitor extends SimpleFileVisitor { + private Path source; + private Path target; + MvFileVisitor(Path source, Path target) { + this.source = source; + this.target = target; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Files.createDirectory(target.resolve(source.relativize(dir))); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.move(file, target.resolve(source.relativize(file))); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + if (exc != null) { + throw exc; + } + Files.delete(dir); + return FileVisitResult.CONTINUE; + } +} + From fa5b6c0d475b94285e14339bebcfa959612da779 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 14:10:20 +0400 Subject: [PATCH 21/30] wrote rm --- .../students/Oktosha/Shell/RmFileVisitor.java | 27 ++++++++++++++++ .../fivt/students/Oktosha/Shell/Shell.java | 31 ++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Shell/RmFileVisitor.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/RmFileVisitor.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/RmFileVisitor.java new file mode 100644 index 000000000..013034cf5 --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/RmFileVisitor.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.Oktosha.Shell; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + +/** + * Class which deletes a directory recursively + */ + +public class RmFileVisitor extends SimpleFileVisitor { + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + if (exc != null) { + throw exc; + } + Files.delete(dir); + return FileVisitResult.CONTINUE; + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index af086a723..6e3f32f28 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -54,6 +54,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "pwd": pwd(cmd.args); break; + case "rm": + rm(cmd.args); + break; case "": break; default: @@ -185,7 +188,7 @@ private void mv(String[] args) throws CommandArgumentSyntaxException, ConsoleUti } catch (NoSuchFileException e) { throw new ConsoleUtilityRuntimeException("mv: " + e.getMessage() + ": No such file or directory", e); } catch (AccessDeniedException e) { - throw new ConsoleUtilityRuntimeException("mkdir: " + e.getMessage() + ": Permission denied", e); + throw new ConsoleUtilityRuntimeException("mv: " + e.getMessage() + ": Permission denied", e); } catch (IOException | SecurityException e) { throw new ConsoleUtilityRuntimeException("mv: something really bad happened " + e.toString(), e); } @@ -197,4 +200,30 @@ private void pwd(String[] args) throws CommandArgumentSyntaxException { } System.out.println(workingDirectory); } + + private void rm(String[] args) throws CommandArgumentSyntaxException, ConsoleUtilityRuntimeException { + if ((args.length == 0) || (args.length > 2) || ((args.length == 2) && !(args[0].equals("-r")))) { + throw new CommandArgumentSyntaxException("rm: Invalid syntax, usage: rm [-r] "); + } + boolean recursively = (args.length == 2); + try { + Path target = workingDirectory.resolve(Paths.get((args.length == 2) ? args[1] : args[0])).toRealPath(); + if (!Files.isDirectory(target)) { + Files.delete(target); + } else { + if (recursively) { + Files.walkFileTree(target, new RmFileVisitor()); + } else { + throw new ConsoleUtilityRuntimeException("rm: " + args[0] + ": Is a directory"); + } + } + } catch (NoSuchFileException e) { + throw new ConsoleUtilityRuntimeException("rm: " + e.getMessage() + ": No such file or directory", e); + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("rm: " + e.getMessage() + ": Permission denied", e); + } catch (IOException | SecurityException e) { + throw new ConsoleUtilityRuntimeException("rm: something really bad happened " + e.toString(), e); + } + + } } From 8d6e78071d2a07d35513ebfb3dfbd4947b0f28b6 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 14:31:24 +0400 Subject: [PATCH 22/30] wrote cp --- .../students/Oktosha/Shell/CpFileVisitor.java | 32 ++++++++++++ .../fivt/students/Oktosha/Shell/Shell.java | 50 ++++++++++++++++++- 2 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/Oktosha/Shell/CpFileVisitor.java diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/CpFileVisitor.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/CpFileVisitor.java new file mode 100644 index 000000000..699e04f1a --- /dev/null +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/CpFileVisitor.java @@ -0,0 +1,32 @@ +package ru.fizteh.fivt.students.Oktosha.Shell; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +/** + * Class which copies a directory recursively + */ + +public class CpFileVisitor extends SimpleFileVisitor { + private Path source; + private Path target; + CpFileVisitor(Path source, Path target) { + this.source = source; + this.target = target; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Files.createDirectory(target.resolve(source.relativize(dir))); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.copy(file, target.resolve(source.relativize(file)), REPLACE_EXISTING); + return FileVisitResult.CONTINUE; + } +} diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 6e3f32f28..9aa432cba 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -39,6 +39,9 @@ public void run(Command cmd) throws CommandIsNotSupportedException, case "cd": cd(cmd.args); break; + case "cp": + cp(cmd.args); + break; case "exit": exit(cmd.args); break; @@ -107,7 +110,51 @@ private void cd(String[] args) throws CommandArgumentSyntaxException, throw new ConsoleUtilityRuntimeException("cd: something really bad happened " + e.toString(), e); } } - + + private void cp(String[] args) throws CommandArgumentSyntaxException, ConsoleUtilityRuntimeException { + if ((args.length < 2) || (args.length > 3) || ((args.length == 3) && !(args[0].equals("-r")))) { + throw new CommandArgumentSyntaxException("cp: Invalid syntax, usage: cp [-r] "); + } + boolean recursively = (args.length == 3); + try { + Path source = workingDirectory.resolve(Paths.get((args.length == 3) ? args[1] : args[0])).toRealPath(); + Path target = workingDirectory.resolve(Paths.get((args.length == 3) ? args[2] : args[1])); + + if (Files.exists(target) && source.equals(target.toRealPath())) { + return; + } + + if (Files.isDirectory(source)) { + if (recursively) { + if (Files.exists(target)) { + if (Files.isDirectory(target)) { + Files.walkFileTree(source, new CpFileVisitor(source, target.resolve(source.getFileName()))); + } else { + throw new ConsoleUtilityRuntimeException("cp:" + args[2] + ": Not a directory"); + } + } else { + Files.walkFileTree(source, new CpFileVisitor(source, target)); + } + } else { + throw new ConsoleUtilityRuntimeException("cp:" + args[1] + ": Is a directory"); + } + } else { + if (Files.exists(target) && Files.isDirectory(target)) { + Files.copy(source, target.resolve(source.getFileName()), REPLACE_EXISTING); + } else { + Files.copy(source, target, REPLACE_EXISTING); + } + } + } catch (NoSuchFileException e) { + throw new ConsoleUtilityRuntimeException("cp: " + e.getMessage() + ": No such file or directory", e); + } catch (AccessDeniedException e) { + throw new ConsoleUtilityRuntimeException("cp: " + e.getMessage() + ": Permission denied", e); + } catch (IOException | SecurityException e) { + throw new ConsoleUtilityRuntimeException("cp: something really bad happened " + e.toString(), e); + } + + } + private void exit(String[] args) throws CommandArgumentSyntaxException { if (args.length != 0) { throw new CommandArgumentSyntaxException("exit: too many arguments"); @@ -224,6 +271,5 @@ private void rm(String[] args) throws CommandArgumentSyntaxException, ConsoleUti } catch (IOException | SecurityException e) { throw new ConsoleUtilityRuntimeException("rm: something really bad happened " + e.toString(), e); } - } } From aac22379ec59d0fc99be1a61ca63dfe67c5894b5 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 14:45:39 +0400 Subject: [PATCH 23/30] tested and fixed minor bags --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 9aa432cba..881e36350 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -136,7 +136,7 @@ private void cp(String[] args) throws CommandArgumentSyntaxException, ConsoleUti Files.walkFileTree(source, new CpFileVisitor(source, target)); } } else { - throw new ConsoleUtilityRuntimeException("cp:" + args[1] + ": Is a directory"); + throw new ConsoleUtilityRuntimeException("cp:" + args[0] + ": Is a directory"); } } else { if (Files.exists(target) && Files.isDirectory(target)) { From 0043c9050cfa5bb0c25ae1117b9c95194da381bb Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 16:00:55 +0400 Subject: [PATCH 24/30] Revert "deleted everything exept my source from the branch Shell" This reverts commit 5aa7efd647d315c5f33cb329ded09a3cbf6b7002. Conflicts: build.xml --- LICENSE | 24 +++++++++ README.md | 22 ++++++++ github-workflow.md | 16 ++++++ tasks/01-Calculator.md | 19 +++++++ tasks/01-Shell.md | 113 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 194 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 github-workflow.md create mode 100644 tasks/01-Calculator.md create mode 100644 tasks/01-Shell.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..f87793701 --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2014, Dmitriy Komanov +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/README.md b/README.md new file mode 100644 index 000000000..5040fedf1 --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# Программирование на языке JAVA + +Курс лекций и семинаров для студентов второго курса ФизТеха, факультет +[ФИВТ](http://fivt.fizteh.ru) на 2014 год. + +## Семинары +В папке [tasks](tasks) находятся описания заданий на +семинары. Для написания программ необходимо руководствоваться [соглашениями +по оформлению кода](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) +от Oracle (Code Conventions). + +В документе [github-workflow](github-workflow.md) описаны +общие правила по ведению задач на github, а также упрощение жизни с помощью утилиты +[checkstyle](http://checkstyle.sourceforge.net/), которая проверяет код на соответствие +Code Conventions. + +## Список литературы +* Брюс Эккель — Философия Java (Thinking in Java) +* Brian Goetz — Java Concurrency in Practive (продвинутая книжка +по многопоточности в Java) +* [Спецификации по JVM и JLS](http://docs.oracle.com/javase/specs/index.html) +* [Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) diff --git a/github-workflow.md b/github-workflow.md new file mode 100644 index 000000000..e1ae4cab3 --- /dev/null +++ b/github-workflow.md @@ -0,0 +1,16 @@ +## Workflow работы с github + +Каждый студент делает [fork](https://help.github.com/articles/fork-a-repo) репозитория ```fizteh-java-2014```. Работа +ведётся в собственном репозитории, в директории ```src/ru/fizteh/fivt/students//```. + +После того, как задание выполнено и протестировано в собственном репозитории, необходимо создать +[pull request](https://help.github.com/articles/using-pull-requests) в репозиторий ```fizteh-java-2014```. В заголовке +к pull request необходимо написать: ```Имя Фамилия, № группы, задание``` (например, ```Василий Иванов, 123, Shell```). +Также необходимо назначить pull request на своего семинариста. + +В одном pull request должно быть решение только одной задачи. Если хочется сдавать параллельно несколько заданий, +необходимо создавать бранчи и делать pull request из бранчей. + +Чтобы сократить количество итераций на проверку задания, полезно самостоятельно удостовериться, что Code Conventions +соблюдены. Для этого нужно запустить сборку проекта с помощью ```ant checkstyle```. Вместо этого можно поставить +соответствующий плагин в IDE и настроить этот плагин на конфигурационный файл ```bin/checkstyle-rules.xml```. diff --git a/tasks/01-Calculator.md b/tasks/01-Calculator.md new file mode 100644 index 000000000..d16049676 --- /dev/null +++ b/tasks/01-Calculator.md @@ -0,0 +1,19 @@ +## Калькулятор +Консольное приложение, на вход принимает выражение как параметр : +```bash +java Calculator "-(3 + 5.5) * 2 - 20/(15 - 5)" +``` + +Результат работы приложения -- результат выражения: +``` +-19 +``` + +Поддерживаемые операции: ```+ - * /```. Приоритет операций -- математический +(скобки, потом унарное отрицание, потом умножение/деление, потом сложение/вычитание). + +В случае неправильных входных данных приложение должно вывести понятное описание +ошибки. + +Ограничения: не использовать встроенные скриптовые движки и кодо- или байткод генерацию. +Одним словом, парсить вручную. diff --git a/tasks/01-Shell.md b/tasks/01-Shell.md new file mode 100644 index 000000000..a4c6dbda2 --- /dev/null +++ b/tasks/01-Shell.md @@ -0,0 +1,113 @@ +## Shell (Оболочка) +Консольное приложение, частично эмулирующее оболочку +[shell](http://en.wikipedia.org/wiki/Unix_shell). + +``` +java Shell [COMMAND1 [; COMMAND2 ...]] +``` + +Если Shell запускается без параметров, то запускается интерактивный режим, +в котором пользователь может ввести команду (или команды) прямо в консоли. + +Список команд: +* ```cd ``` — change directory, смена +текущей директории. Поддерживаются ```.```, ```..```, относительные и абсолютные +пути +* ```mkdir ``` — создание директории в текущей директории +* ```pwd``` — print working directory, печатает абсолютный путь к текущей +директории +* ```rm [-r] ``` — удаляет указанную в параметрах файл или папку. Если указать параметр ```-r``` то удаляется рекурсивно. +* ```cp [-r] ``` — копирует указанную в параметрах +папку/файл в указанное место. Параметр ```-r``` позволяет копировать рекурсивно. +* ```mv ``` — переносит указанный файл/папку в +новое место (файл на прежнем месте удаляется). В частности переименовывает +файл/папку, если ```source``` и ```destination``` находятся в одной папке +* ```ls``` — печатает содержимое текущей директории +* ```exit``` — выход из приложения +* ```cat ``` — выводит содержимое файла на экран. + +За один раз можно написать несколько команд. Разделителем команд является +```;``` (точка с запятой). + +### Интерактивный режим +В интерактивном режиме должно отображаться "приглашение" — ```$ ``` (знак +доллара и пробел), после которого производится ввод команд. Также в интерактивном +режиме допускается вывод текущей директории перед "приглашением". + +### Пакетный режим +Если запустить консольное приложение с параметрами, то параметры должны +интерпретироваться как команды (все команды должны склеиваться через пробел). +Приложение должно выполнить последовательно все команды и завершиться. + +В случае ошибки команды, приложение должно выводить ошибку в stderr. + +В случае ошибки в любой из команд, приложение должно написать сообщение об +ошибке и завершиться с ненулевым кодом. + +### Вывод команд +Вывод команд имеет строгий формат. Никакого дополнительного вывода в stdout быть +не должно (в финальном коде вся debug-информация должна отсутствовать). + +```(bash) +$ cd /noexistingdir +cd: '/noexistingdir': No such file or directory +$ cd /home/user +$ pwd +/home/user +$ ls +Folder +file.txt +$ mkdir MyFolder +$ ls +Folder +MyFolder +file.txt +$ cp file.txt MyFolder +$ cd MyFolder +$ ls +file.txt +$ mv file.txt file2.txt +$ ls +file2.txt +$ rm file.txt +rm: cannot remove 'file.txt': No such file or directory +$ rm file2.txt +$ ls +$ cd .. +$ ls +Folder +MyFolder +file.txt +$ mv Folder MyFolder +$ ls +MyFolder +file.txt +$ cp MyFolder NewFolder +cp: MyFolder is a directory (not copied). +$ ls +Folder +MyFolder +file.txt +$ cp -r MyFolder NewFolder +$ ls +Folder +MyFolder +NewFolder +file.txt +$ rm NewFolder +rm: NewFolder: is a directory +$ ls +Folder +MyFolder +NewFolder +file.txt +$ rm -r NewFolder +$ ls +Folder +MyFolder +file.txt +$ cat file.text +Hello World! +$ cat wrongfile.txt +cat: wrongfile.txt: No such file or directory +$ exit From e66bdef49b194cb00d949c10ce8ec26d0dcac071 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 16:06:40 +0400 Subject: [PATCH 25/30] renamed --- .../fizteh/fivt/students/Oktosha/Shell/{mvFileVisitor.java => a} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/ru/fizteh/fivt/students/Oktosha/Shell/{mvFileVisitor.java => a} (100%) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/a similarity index 100% rename from src/ru/fizteh/fivt/students/Oktosha/Shell/mvFileVisitor.java rename to src/ru/fizteh/fivt/students/Oktosha/Shell/a From d6e794ebaebbe19a8478a3c525e33b7cdb5311a8 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 16:07:09 +0400 Subject: [PATCH 26/30] renamed --- .../fizteh/fivt/students/Oktosha/Shell/{a => MvFileVisitor.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/ru/fizteh/fivt/students/Oktosha/Shell/{a => MvFileVisitor.java} (100%) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/a b/src/ru/fizteh/fivt/students/Oktosha/Shell/MvFileVisitor.java similarity index 100% rename from src/ru/fizteh/fivt/students/Oktosha/Shell/a rename to src/ru/fizteh/fivt/students/Oktosha/Shell/MvFileVisitor.java From 566fe5161310f38510f249843710374779be831e Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Mon, 6 Oct 2014 19:50:08 +0400 Subject: [PATCH 27/30] fixed bug in cp --- src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java index 881e36350..38e8a5962 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Shell/Shell.java @@ -121,7 +121,9 @@ private void cp(String[] args) throws CommandArgumentSyntaxException, ConsoleUti Path target = workingDirectory.resolve(Paths.get((args.length == 3) ? args[2] : args[1])); if (Files.exists(target) && source.equals(target.toRealPath())) { - return; + throw new ConsoleUtilityRuntimeException("cp:" + source + + " and " + target + + " are identical (not copied)"); } if (Files.isDirectory(source)) { @@ -216,7 +218,7 @@ private void mv(String[] args) throws CommandArgumentSyntaxException, ConsoleUti if (Files.isDirectory(source)) { if (Files.exists(target)) { if (Files.isDirectory(target)) { - Files.walkFileTree(source, new MvFileVisitor(source, target.resolve(source.getFileName()))); + Files.walkFileTree(source, new MvFileVisitor(source, target.resolve(source.getFileName()))); } else { throw new ConsoleUtilityRuntimeException("mv: rename '" + args[0] + "' to '" + args[1] From dae8df751523957fb4276788b7d7f5d10e3af96d Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Tue, 7 Oct 2014 00:04:11 +0400 Subject: [PATCH 28/30] fixed interactive executor, added hasline --- .../fivt/students/Oktosha/Executor/InteractiveExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java index f10d81b7b..86e0f760b 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java @@ -15,7 +15,7 @@ public static void execute(ConsoleUtility utility) { Scanner sc = new Scanner(System.in); System.out.print("$ "); System.out.flush(); - for (; ; ) { + while (sc.hasNextLine()) { String commandsString = sc.nextLine(); try { Command[] commands = parse(commandsString); From 90634e044456f3847e4022df6d0cac284e436709 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Wed, 8 Oct 2014 13:12:02 +0400 Subject: [PATCH 29/30] changed ;; behaviour, now ignored --- src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java index 2acf9bded..41f2c6d7d 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/Executor.java @@ -10,10 +10,7 @@ public abstract class Executor { static final int SYNTAX_ERROR = 1; static final int COMMAND_RUNTIME_ERROR = 2; - protected static Command[] parse(String s) throws ExecutorParseException { - if (s.matches(".*;\\s*;.*")) { - throw new ExecutorParseException(); - } + protected static Command[] parse(String s) { String[] commandStrings = s.split(";"); Command[] res = new Command[commandStrings.length]; for (int i = 0; i < res.length; ++i) { From bef86b4ba010b98c421be93e8c612079357224a2 Mon Sep 17 00:00:00 2001 From: Daria Kolodzey Date: Sat, 11 Oct 2014 12:51:20 +0400 Subject: [PATCH 30/30] fixed compilation error --- .../fivt/students/Oktosha/Executor/InteractiveExecutor.java | 3 --- .../fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java | 3 --- 2 files changed, 6 deletions(-) diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java index 86e0f760b..961f05edf 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/InteractiveExecutor.java @@ -22,9 +22,6 @@ public static void execute(ConsoleUtility utility) { for (Command cmd : commands) { utility.run(cmd); } - } catch (ExecutorParseException e) { - System.err.println("invalid syntax: empty command between two semicolons"); - System.err.flush(); } catch (ConsoleUtilityException e) { System.err.println(e.getMessage()); System.err.flush(); diff --git a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java index af6c1b73b..af2072710 100644 --- a/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java +++ b/src/ru/fizteh/fivt/students/Oktosha/Executor/PackageExecutor.java @@ -21,9 +21,6 @@ public static void execute(ConsoleUtility utility, String[] args) { for (Command cmd : commands) { utility.run(cmd); } - } catch (ExecutorParseException e) { - System.err.println("invalid syntax: empty command between two semicolons"); - System.exit(Executor.SYNTAX_ERROR); } catch (ConsoleUtilitySyntaxException e) { System.err.println(e.getMessage()); System.exit(Executor.SYNTAX_ERROR);