Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/ConsoleRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.javarush.popkovdmitriy;

import com.javarush.popkovdmitriy.console.ConsoleApp;
import com.javarush.popkovdmitriy.console.Menu;
import com.javarush.popkovdmitriy.controller.MainController;
import com.javarush.popkovdmitriy.util.PathBuilder;

import java.util.Scanner;

public class ConsoleRunner {

public static void main(String[] args) {
//build console app
Scanner input = new Scanner(System.in);
Menu inputmenu = new Menu(input);
ConsoleApp application = new ConsoleApp(inputmenu, input);
PathBuilder readFILE = new PathBuilder(application);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Странное имя для переменной



MainController mainController = new MainController(readFILE.inputFilePath, application.shift, inputmenu.inputmenu);
while (mainController.pick_upShift == 1) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что такое один


new MainController(readFILE.inputFilePath, MainController.shift, inputmenu.inputmenu);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Рождение объекта и выполнение каких-то действий в нём обычно два разных вызова

}
}



}


74 changes: 74 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/command/BruteForce.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.javarush.popkovdmitriy.command;

import com.javarush.popkovdmitriy.constant.Const;
import com.javarush.popkovdmitriy.exeption.AppExeption;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class BruteForce {
public static boolean commonEmtyWords;


public static String bruteforce(String text, int shift) {

return Encode.encrypt(text, (-1 * shift));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот здесь нужно было сделать логику вычисления ключа, она ожидается именно здесь


}


public static Set<String> findCommonWords() {
Set<String> wordsInFile1_buff = BruteForce.findCommonWords1();
Set<String> commonWords_buff = BruteForce.findCommonWords2(wordsInFile1_buff);
BruteForce.commonEmtyWords = commonWords_buff.isEmpty();
return commonWords_buff;
}

public static Set<String> findCommonWords1() {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень странное и непонятное название метода

Set<String> wordsInFile1 = new HashSet<>();

try (BufferedReader reader1 = new BufferedReader(new FileReader(Const.METRIKA_PATH))) {
String line;
while ((line = reader1.readLine()) != null) {

String[] words = line.split("\\s+");
for (String word : words) {
wordsInFile1.add(word.toLowerCase());
}
}
} catch (IOException e) {
throw new AppExeption(e.getMessage());
}
return wordsInFile1;
}

public static Set<String> findCommonWords2(Set<String> wordsInFile1) {
Set<String> commonWords = new HashSet<>();

try (BufferedReader reader2 = new BufferedReader(new FileReader(Const.BRUTFORCE_PATH))) {
String line;
while ((line = reader2.readLine()) != null) {
String[] words = line.split("\\s+");
for (String word : words) {
if (wordsInFile1.contains(word.toLowerCase())) {
commonWords.add(word.toLowerCase());
}
}
}

} catch (IOException e) {
throw new AppExeption(e.getMessage());
}

return commonWords;
}

public static int bruteforceShift(int shift) {
++shift;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это можно сделать одной строкой

return shift;
}

}
9 changes: 9 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/command/Decode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.javarush.popkovdmitriy.command;

public class Decode {

public static String decrypt(String text, int shift) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Размещать всю логику в статические методы не самая лучшая практика


return Encode.encrypt(text, (-1*shift));
}
}
66 changes: 66 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/command/Encode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.javarush.popkovdmitriy.command;




import static com.javarush.popkovdmitriy.constant.Alphabet.*;

public class Encode {


public static String encrypt(String text, int shift) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Из-за того что основной метод статический, приходится всё остальное логику тоже делать статической, в будущем мы будем изучать тестирование и будет видно что данный подход сильно мешает тестированию приложений

StringBuilder encryptedText = new StringBuilder();

for (char character : text.toCharArray()) {
encryptedText.append(encryptCharacter(character, shift));
}

return encryptedText.toString();
}

private static char encryptCharacter(char character, int shift) {

if (( character >='a' && character <='z')||( character >='A' && character <='Z')) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Какой смысл в этих пустых строчках

if (Character.isLowerCase(character)) {

return encryptInAlphabet(character, LATIN_ALPHABET, shift);
} else if (Character.isUpperCase(character)) {

return encryptInAlphabet(Character.toLowerCase(character), LATIN_ALPHABET, shift);
}
}

if ( character >='а' && character <='я')

{

return encryptInAlphabet(character, RUSSIAN_ALPHABET, shift);
} else
if ( character >='А' && character <='Я'){
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Буква Ë находится не между этими двумя

return encryptInAlphabet(character, RUSSIAN_ALPHABET_UPPER, shift);
}

return encryptInAlphabet(character, SYMBOLS, shift);
}

private static char encryptInAlphabet(char character, char[] alphabet, int shift) {
int index = -1;


for (int i = 0; i< alphabet.length ;i++){
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы не было таких циклов лучше использовать карты

if (alphabet[i] == character) {
index = i;
break;
}
}
if (index != -1) {
int newIndex = (index + shift) % alphabet.length;
return alphabet[(newIndex + alphabet.length) % alphabet.length];
}


return character;
}

}
11 changes: 11 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/command/Exit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.javarush.popkovdmitriy.command;


public class Exit {
public static void exit(){
System.exit(0);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такой способ выхода никогда не пишут в реальных приложениях

}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что-то с форматированием


}


67 changes: 67 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/console/ConsoleApp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.javarush.popkovdmitriy.console;

import com.javarush.popkovdmitriy.command.Exit;
import com.javarush.popkovdmitriy.exeption.AppExeption;

import java.util.Scanner;

import static com.javarush.popkovdmitriy.console.Messages.outMode;

public class ConsoleApp {
public String filename;
private final Scanner scanner;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять что-то с форматированием

public Menu inputmenu_Console;
public int shift;

public ConsoleApp(Menu inputmenu,Scanner scanner) {
this.scanner=scanner;
this.inputmenu_Console=inputmenu;
if (inputmenu.inputmenu==3) {
Exit.exit();
}
inputShift(inputmenu);





}



private String getinputPath() {

this.filename=getScanner().nextLine();


return this.filename;
}


public Scanner getScanner() {
return scanner;
}

public void inputShift(Menu inputmenu){
System.out.print("Введите имя файла для режима "+ outMode[inputmenu.inputmenu]+" " );
this.filename =getinputPath();
if (inputmenu.inputmenu!=2){
String shift1;

System.out.print("Введите ключ ");
shift1=getScanner().nextLine();
try {

this.shift=Integer.parseInt(shift1);
} catch (NumberFormatException e) {
throw new AppExeption(e.getMessage());
}
}else {
this.shift=1;

}

}

}

51 changes: 51 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/console/Menu.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.javarush.popkovdmitriy.console;
import java.util.Scanner;

import static com.javarush.popkovdmitriy.console.Messages.*;

public class Menu {

public Scanner scanner;
public int inputmenu;




public Menu(Scanner input) {
int mode;
this.scanner=input;
String inputmode;

System.out.println(EncodeMenu + " 1");
System.out.println(DecodeMenu + " 2");
System.out.println( BruteForce+ " 3");
System.out.println(ExitMenu + " 4");
System.out.print("Выбран режим ");
do{
inputmode = input.nextLine();


mode = switch (inputmode) {
case "1" -> 0;
case "2" -> 1;
case "3" -> 2;
case "4" -> 3;
// case "5" -> 4;
default -> {

System.out.println("INCORRECT_SELECTION");

yield -1;

}
};


} while (mode < 0) ;

System.out.println(outMode[mode]);
this.inputmenu=mode;
}


}
10 changes: 10 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/console/Messages.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.javarush.popkovdmitriy.console;

public interface Messages {
String EncodeMenu="Кодирование текста";
String DecodeMenu="Декодирование текста";
String BruteForce="Взлом приложения";
String ExitMenu="Выход из приложения";
String[] outMode=new String[]{EncodeMenu,DecodeMenu,BruteForce,ExitMenu};

}
13 changes: 13 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/constant/Alphabet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.javarush.popkovdmitriy.constant;



public class Alphabet {


public static final char[] LATIN_ALPHABET ="abcdefghijklmnopqrstuvwxyz".toCharArray();
public static final char[] RUSSIAN_ALPHABET = "абвгдежзийклмнопрстуфхцчшщъыьэюя".toCharArray();
public static final char[] RUSSIAN_ALPHABET_UPPER ="АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".toCharArray();
public static final char[] SYMBOLS = "☮.,”’:-!? ".toCharArray();

}
17 changes: 17 additions & 0 deletions src/main/java/com/javarush/popkovdmitriy/constant/Const.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.javarush.popkovdmitriy.constant;

import java.io.File;

import static java.lang.System.getProperty;

public interface Const {
String TXT_FOLDER = getProperty("user.dir") +
File.separator +
"text" +
File.separator;

String ENCRYPTED_PATH=TXT_FOLDER+"encryptedText.txt";
String DECRYPTED_PATH=TXT_FOLDER+"decryptedText.txt";
String METRIKA_PATH=TXT_FOLDER+"dict.txt";
String BRUTFORCE_PATH=TXT_FOLDER+"brutforsText.txt";
}
Loading