-
Notifications
You must be signed in to change notification settings - Fork 47
Golikov - 3 tasks complite. #41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
05e6b0b
dcb60bc
b7387c9
c26ec46
a016e48
79553b9
19c6671
c8313c9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.javarush.golikov; | ||
|
|
||
| import com.javarush.golikov.controller.Controller; | ||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.view.ShowMenu; | ||
|
|
||
| public class Application { | ||
| private final Controller controller = new Controller(); | ||
| private final ShowMenu showMenu = new ShowMenu(); | ||
|
|
||
| public Result run() { | ||
| int menuIndex = showMenu.getMenuItem(); | ||
| String[] parametrises = showMenu.getParameterises(menuIndex == 0 || menuIndex == 1); | ||
| return controller.doAction(menuIndex, parametrises); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package com.javarush.golikov; | ||
|
|
||
| import com.javarush.golikov.entite.Result; | ||
|
|
||
| public class ConsoleRunner { | ||
| public static void main(String[] args) { | ||
| Application application = new Application(); | ||
| Result result = application.run(); | ||
| System.out.println(result); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package com.javarush.golikov.constatnts; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Опечатка в названии пакета: |
||
|
|
||
| import java.io.File; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| public class Constants { | ||
| private static final String ruAlphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; | ||
| private static final String specialCharacters = "\n.,\":-!? "; | ||
|
|
||
| public static final char[] ALPHABET = (ruAlphabet.toLowerCase() + specialCharacters).toCharArray(); | ||
| public static final String DEFAULT_FOLDER = System.getProperty("user.dir") + File.separator + "text" + File.separator; | ||
|
|
||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поле |
||
| public static final List<Character> ALPHABET_LIST = new ArrayList<>(); | ||
|
|
||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вместо ручного заполнения списка в static-блоке используйте Stream API: |
||
| static { | ||
| for(Character simbol : ALPHABET) ALPHABET_LIST.add(simbol); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package com.javarush.golikov.controller; | ||
|
|
||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
| import com.javarush.golikov.menuComands.BruteForce; | ||
| import com.javarush.golikov.menuComands.MenuCommands; | ||
| import com.javarush.golikov.menuComands.Decoding; | ||
| import com.javarush.golikov.menuComands.Encryption; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| public class Actions { | ||
|
|
||
| private final Map<Integer, MenuCommands> actionMap = new HashMap<>(); | ||
|
|
||
| public Actions() { | ||
| actionMap.put(0, new Encryption()); | ||
| actionMap.put(1, new Decoding()); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Используйте |
||
| actionMap.put(2, new BruteForce()); | ||
| } | ||
|
|
||
| public MenuCommands findAction(int actionIndex) { | ||
| if (actionMap.containsKey(actionIndex)) { | ||
| try { | ||
| return actionMap.get(actionIndex); | ||
| } catch (IllegalArgumentException e) { | ||
| throw new ApplicationExceptions("Пункт меню не реализован!", e); | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Метод |
||
| } else throw new ApplicationExceptions("Пункт меню не реализован!"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package com.javarush.golikov.controller; | ||
|
|
||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
| import com.javarush.golikov.menuComands.MenuCommands; | ||
|
|
||
|
|
||
| public class Controller { | ||
| public Result doAction(int actionNumber, String[] parametrises) { | ||
| Actions actions = new Actions(); | ||
| try{ | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Объект |
||
| MenuCommands menuCommands = actions.findAction(actionNumber); | ||
| return menuCommands.execute(parametrises); | ||
| } catch (IllegalArgumentException | ApplicationExceptions e) { | ||
| return new Result(e.getMessage(), "Error"); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.javarush.golikov.entite; | ||
|
|
||
| public record Result(String message, String resultCode) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Record автоматически генерирует |
||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Result{" + | ||
| "message='" + message + '\'' + | ||
| ", resultCode='" + resultCode + '\'' + | ||
| '}'; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.javarush.golikov.exception; | ||
|
|
||
| public class ApplicationExceptions extends RuntimeException { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Название класса во множественном числе ( |
||
|
|
||
| public ApplicationExceptions(String message) { | ||
| super(message); | ||
| } | ||
|
|
||
| public ApplicationExceptions(String message, Throwable cause) { | ||
| super(message, cause); | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package com.javarush.golikov.menuComands; | ||
|
|
||
| import com.javarush.golikov.constatnts.Constants; | ||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
|
|
||
| import java.io.BufferedReader; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| public class BruteForce extends Commands { | ||
| @Override | ||
| public Result execute(String[] parametrises) { | ||
| String source = parametrises[0]; | ||
| if (Files.isDirectory(Path.of(source))) { | ||
| source += "output.txt"; | ||
| } | ||
| String target = parametrises[1]; | ||
| if (Files.isDirectory(Path.of(target))) { | ||
| target += "bfresult.txt"; | ||
| } | ||
| int bestKey = 0; | ||
| int bestSpaceCount = 0; | ||
| char space = ' '; | ||
| for (int key = 0; key < Constants.ALPHABET.length; key++) { | ||
| int spaceCount = countCharInFileWithKey(source, key, space); | ||
| if (spaceCount > bestSpaceCount) { | ||
| bestSpaceCount = spaceCount; | ||
| bestKey = key; | ||
| } | ||
| } | ||
| return doCommand(source, target, bestKey); | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поиск лучшего ключа можно реализовать через Stream API: |
||
|
|
||
| private int countCharInFileWithKey(String encryptedFilename, int key, char fixChar) { | ||
| int spaceCount = 0; | ||
| Path path = Path.of(encryptedFilename); | ||
| try (BufferedReader reader = Files.newBufferedReader(path)) { | ||
| int value; | ||
| while ((value = reader.read()) > -1) { | ||
| char character = (char) value; | ||
| if (Constants.ALPHABET_LIST.contains(character)) { | ||
| int index = Constants.ALPHABET_LIST.indexOf(character); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вызов |
||
| index = (index + key + Constants.ALPHABET.length) % Constants.ALPHABET.length; | ||
| if (Constants.ALPHABET[index] == fixChar) { | ||
| spaceCount++; | ||
| } | ||
| } | ||
| } | ||
| } catch (IOException e) { | ||
| throw new ApplicationExceptions("Файл не найден" + encryptedFilename, e); | ||
| } | ||
| return spaceCount; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package com.javarush.golikov.menuComands; | ||
|
|
||
| import com.javarush.golikov.constatnts.Constants; | ||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
|
|
||
| import java.io.BufferedReader; | ||
| import java.io.BufferedWriter; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| public abstract class Commands implements MenuCommands { | ||
| public Result doCommand(String source, String target, int key) { | ||
| Path sourceFile = Path.of(source); | ||
| Path targetFile = Path.of(target); | ||
|
|
||
| try (BufferedReader fileReader = Files.newBufferedReader(sourceFile); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вместо конкатенации путей через |
||
| BufferedWriter fileWriter = Files.newBufferedWriter(targetFile)) { | ||
| int value; | ||
| int length = Constants.ALPHABET.length; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использование |
||
| while ((value = fileReader.read()) > -1) { | ||
| char character = (char) value; | ||
| character = Character.toLowerCase(character); | ||
| if (Constants.ALPHABET_LIST.contains(character)) { | ||
| int index = Constants.ALPHABET_LIST.indexOf(character); | ||
| index = (index + key + Math.abs(key) * length) % length; | ||
| fileWriter.write(Constants.ALPHABET[index]); | ||
| } else if (character == '\n') { | ||
| fileWriter.write(character); | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Для вычисления индекса при отрицательных сдвигах используйте |
||
| } | ||
| } catch (IOException e) { | ||
| throw new ApplicationExceptions("Файл не найден" + e.getMessage(), e); | ||
| } | ||
| return new Result(this.getClass().getSimpleName(), "Ok"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.javarush.golikov.menuComands; | ||
|
|
||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
|
|
||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| public class Decoding extends Commands { | ||
|
|
||
| @Override | ||
| public Result execute(String[] parametrises) { | ||
| String source = parametrises[0]; | ||
| if (Files.isDirectory(Path.of(source))) { | ||
| source += "output.txt"; | ||
| } | ||
| String target = parametrises[1]; | ||
| if (Files.isDirectory(Path.of(target))) { | ||
| target += "decoding.txt"; | ||
| } | ||
| int key; | ||
| try { | ||
| key = Integer.parseInt(parametrises[2]); | ||
| } catch (NumberFormatException e) { | ||
| throw new ApplicationExceptions("Неверный ключ"); | ||
| } | ||
| return doCommand(source, target, key * -1); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.javarush.golikov.menuComands; | ||
|
|
||
| import com.javarush.golikov.entite.Result; | ||
| import com.javarush.golikov.exception.ApplicationExceptions; | ||
|
|
||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| public class Encryption extends Commands { | ||
|
|
||
| @Override | ||
| public Result execute(String[] parametrises) { | ||
| String source = parametrises[0]; | ||
| if (Files.isDirectory(Path.of(source))) { | ||
| source += "text.txt"; | ||
| } | ||
| String target = parametrises[1]; | ||
| if (Files.isDirectory(Path.of(target))) { | ||
| target += "output.txt"; | ||
| } | ||
| int key; | ||
| try{ | ||
| key = Integer.parseInt(parametrises[2]); | ||
| } catch(NumberFormatException e){ | ||
| throw new ApplicationExceptions("Неверный ключ"); | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Дублирование логики парсинга ключа и проверки путей в |
||
| return doCommand(source, target, key); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package com.javarush.golikov.menuComands; | ||
|
|
||
| import com.javarush.golikov.entite.Result; | ||
|
|
||
| public interface MenuCommands { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Используйте |
||
| Result execute(String[] parametrises); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| package com.javarush.golikov.view; | ||
|
|
||
| import com.javarush.golikov.constatnts.Constants; | ||
|
|
||
| import java.util.Scanner; | ||
|
|
||
|
|
||
| public class ShowMenu { | ||
| private final Scanner scanner = new Scanner(System.in); | ||
|
|
||
| public int getMenuItem() { | ||
| int item; | ||
| do { | ||
| System.out.println("Выберите пункт меню\n" + | ||
| """ | ||
| 1. Шифрование | ||
| 2. Дешифровка | ||
| 3. "Brute force" | ||
| 4. Анализ | ||
| 5. Выход | ||
| """ ); | ||
| String input = scanner.nextLine(); | ||
| item = switch (input) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использование |
||
| case "1" -> 0; | ||
| case "2" -> 1; | ||
| case "3" -> 2; | ||
| case "4" -> 3; | ||
| case "5" -> 4; | ||
| default -> { | ||
| System.out.println("Неверный ввод. Повторите ввод"); | ||
| yield -1; | ||
| } | ||
| }; | ||
| } while (item < 0); | ||
| return item; | ||
| } | ||
|
|
||
| public String[] getParameterises(boolean isKeyNeeded) { | ||
| String[] parameterises = new String[3]; | ||
| if (isKeyNeeded){ | ||
| System.out.println("Введите ключ шифрования/дешифрования"); | ||
| parameterises[2] = scanner.nextLine(); | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использование |
||
| System.out.println("Введите путь исходного файла по умолчанию директория пользователя папка text"); | ||
| String innFile = scanner.nextLine(); | ||
| parameterises[0] = innFile.isEmpty() ? Constants.DEFAULT_FOLDER : innFile; | ||
| System.out.println("Введите путь конечного файла по умолчанию директория пользователя папка text"); | ||
| String outFile = scanner.nextLine(); | ||
| parameterises[1] = outFile.isEmpty() ? Constants.DEFAULT_FOLDER : innFile; | ||
| return parameterises; | ||
| } | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Логическая ошибка: переменной |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Условие
menuIndex == 0 || menuIndex == 1является 'хрупким'. Если порядок в меню изменится, логика сломается. Используйте полиморфизм для определения необходимости ключа.