diff --git a/.idea/checkstyle-idea.xml b/.idea/checkstyle-idea.xml new file mode 100644 index 0000000..21a0f73 --- /dev/null +++ b/.idea/checkstyle-idea.xml @@ -0,0 +1,16 @@ + + + + + + \ No newline at end of file diff --git a/.idea/dictionaries/excen.xml b/.idea/dictionaries/excen.xml new file mode 100644 index 0000000..0758436 --- /dev/null +++ b/.idea/dictionaries/excen.xml @@ -0,0 +1,7 @@ + + + + abcdefghijklmnopqrstuvwxyz + + + \ No newline at end of file diff --git a/.idea/google-java-format.xml b/.idea/google-java-format.xml new file mode 100644 index 0000000..8b57f45 --- /dev/null +++ b/.idea/google-java-format.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0_RC1.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0.xml similarity index 57% rename from .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0_RC1.xml rename to .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0.xml index f8bf2aa..7efb7ad 100644 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0_RC1.xml +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_5_6_0.xml @@ -1,13 +1,13 @@ - + - + - + - + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0_RC1.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0.xml similarity index 65% rename from .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0_RC1.xml rename to .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0.xml index 4d72560..be380a5 100644 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0_RC1.xml +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_api_5_6_0.xml @@ -1,13 +1,13 @@ - + - + - + - + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0_RC1.xml b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0.xml similarity index 64% rename from .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0_RC1.xml rename to .idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0.xml index 1d54e61..227bc44 100644 --- a/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0_RC1.xml +++ b/.idea/libraries/Maven__org_junit_jupiter_junit_jupiter_engine_5_6_0.xml @@ -1,13 +1,13 @@ - + - + - + - + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0_RC1.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0.xml similarity index 63% rename from .idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0_RC1.xml rename to .idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0.xml index a5016bb..8e5d3f2 100644 --- a/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0_RC1.xml +++ b/.idea/libraries/Maven__org_junit_platform_junit_platform_commons_1_6_0.xml @@ -1,13 +1,13 @@ - + - + - + - + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0_RC1.xml b/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0.xml similarity index 63% rename from .idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0_RC1.xml rename to .idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0.xml index a74d90f..2f36d10 100644 --- a/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0_RC1.xml +++ b/.idea/libraries/Maven__org_junit_platform_junit_platform_engine_1_6_0.xml @@ -1,13 +1,13 @@ - + - + - + - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 24b5a2d..d6091e9 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -19,7 +19,7 @@ - + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7..78cface 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -1,5 +1,10 @@ + + + + + diff --git a/homework.db b/homework.db index 255eaf1..354419f 100644 Binary files a/homework.db and b/homework.db differ diff --git a/task2/src/main/java/A.java b/task2/src/main/java/A.java index 26a402e..54991e8 100644 --- a/task2/src/main/java/A.java +++ b/task2/src/main/java/A.java @@ -1,12 +1,12 @@ public class A { - static { - System.out.println("LOL!"); - } + static int a; - public A() { - System.out.println("CONSTRUCTOR"); - } + static { + System.out.println("LOL!"); + } - static int a; + public A() { + System.out.println("CONSTRUCTOR"); + } } diff --git a/task2/src/main/java/DBClass.java b/task2/src/main/java/DBClass.java index 273c05d..2479ae2 100644 --- a/task2/src/main/java/DBClass.java +++ b/task2/src/main/java/DBClass.java @@ -1,29 +1,32 @@ import java.sql.*; -import java.util.Arrays; - public class DBClass { - - public static void main(String[] args) throws ClassNotFoundException, SQLException { - Class.forName("org.sqlite.JDBC"); - Connection conn = DriverManager - .getConnection("jdbc:sqlite:homework.db"); - Statement stmt = conn.createStatement(); - String fieldName1 = "id"; - String fieldName2 = "msg"; - stmt.execute("CREATE TABLE IF NOT EXISTS lol(" + fieldName1 + " INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + fieldName2 + " TEXT);"); - String type = "'Laptop'"; - ResultSet rs = stmt.executeQuery("SELECT DISTINCT * FROM Product WHERE type=" + type + ";"); - while (rs.next()) { - System.out.println(rs.getString("maker") + " " - + rs.getInt("model") + " " + rs.getString("type")); - } - stmt.execute("CREATE table IF NOT EXISTS users(id INTEGER, name TEXT);"); - //PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id, name) values(?, ?);"); - for (int i = 0; i < 100; i++) { - User u = new User(i+1, "Ivan " + (i + 1)); - stmt.executeUpdate("INSERT INTO users(id, name) VALUES (" + u.getId() +", '" +u.getName() +"');"); - } + public static void main(String[] args) throws ClassNotFoundException, SQLException { + + Class.forName("org.sqlite.JDBC"); + Connection conn = DriverManager.getConnection("jdbc:sqlite:homework.db"); + Statement stmt = conn.createStatement(); + String fieldName1 = "id"; + String fieldName2 = "msg"; + stmt.execute( + "CREATE TABLE IF NOT EXISTS lol(" + + fieldName1 + + " INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + + fieldName2 + + " TEXT);"); + String type = "'Laptop'"; + ResultSet rs = stmt.executeQuery("SELECT DISTINCT * FROM Product WHERE type=" + type + ";"); + while (rs.next()) { + System.out.println( + rs.getString("maker") + " " + rs.getInt("model") + " " + rs.getString("type")); + } + stmt.execute("CREATE table IF NOT EXISTS users(id INTEGER, name TEXT);"); + // PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id, name) values(?, ?);"); + for (int i = 0; i < 100; i++) { + User u = new User(i + 1, "Ivan " + (i + 1)); + stmt.executeUpdate( + "INSERT INTO users(id, name) VALUES (" + u.getId() + ", '" + u.getName() + "');"); } + } } diff --git a/task2/src/main/java/DBUtility.java b/task2/src/main/java/DBUtility.java index 0e67b06..4a65454 100644 --- a/task2/src/main/java/DBUtility.java +++ b/task2/src/main/java/DBUtility.java @@ -1,74 +1,130 @@ - - -import java.sql.*; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; public class DBUtility { - /* - * Каждый из тасков решается одним SQL запросом - */ - - /* - Создать таблицу принтеры, Printer(id INTEGER AI PK U, model INTEGER, color TEXT, type TEXT, price INTEGER) - добавить в нее 3 записи: - 1 1012 col laser 20000 (производитель HP) - 2 1010 bw jet 5000 (производитель Canon) - 3 1010 bw jet 5000 (производитель Canon) - Каждая вставка в таблицу принтер должна отражаться добавлением записи в таблицу продукт - */ - - - void AddPrinters(Statement stmt){ - // TODO: 16.12.2019 + /* + * Каждый из тасков решается одним SQL запросом + */ + + /* + Создать таблицу принтеры, Printer(id INTEGER AI PK U, model INTEGER, color TEXT, type TEXT, price INTEGER) + добавить в нее 3 записи: + 1 1012 col laser 20000 (производитель HP) + 2 1010 bw jet 5000 (производитель Canon) + 3 1010 bw jet 5000 (производитель Canon) + Каждая вставка в таблицу принтер должна отражаться добавлением записи в таблицу продукт + */ + + public void createPrinterTable(Connection con, Statement stmt) throws SQLException { + String query = + "create table if not exists Printer(id INTEGER AI PK U, model INTEGER, color TEXT, type TEXT, price INTEGER)"; + stmt.execute(query); + AddPrinters(stmt); + } + + void AddPrinters(Statement stmt) throws SQLException { + String addPrinter1 = + "INSERT INTO Printer(id, model, color, type, price) VALUES(1, 1012, 'col', 'laser', 20000);"; + String addPrinter2 = + "INSERT INTO Printer(id, model, color, type, price) VALUES(2, 1010, 'bw', 'jet', 5000);"; + String addPrinter3 = + "INSERT INTO Printer(id, model, color, type, price) VALUES(3, 1010, 'bw', 'jet', 5000);"; + stmt.addBatch(addPrinter1); + stmt.addBatch(addPrinter2); + stmt.addBatch(addPrinter3); + stmt.executeBatch(); + } + + /* + * Метод должен вернуть список уникальных моделей PC дороже 15 тысяч + */ + + public ArrayList selectExpensivePC(Statement stmt) { + ArrayList result = new ArrayList<>(); + try (ResultSet resultSet = + stmt.executeQuery("select distinct model from PC where price > 15000")) { + while (resultSet.next()) { + result.add(resultSet.getString(1)); + } + } catch (SQLException e) { + e.printStackTrace(); } - - - public void createPrinterTable(Connection con, Statement stmt){ - // TODO: 16.12.2019 + return result; + } + + /* + * Метод должен вернуть список id ноутов, скорость процессора + * которых выше чем 2500 + */ + + public ArrayList selectQuickLaptop(Statement stmt) { + ArrayList result = new ArrayList<>(); + try { + try (ResultSet resultSet = stmt.executeQuery("select id from laptop l where speed > 2500")) { + while (resultSet.next()) { + result.add(resultSet.getInt(1)); + } + } + } catch (SQLException e) { + e.printStackTrace(); } - - /* - * Метод должен вернуть список уникальных моделей PC дороже 15 тысяч - */ - - public ArrayList selectExpensivePC(Statement stmt){ - //todo - return null; + return result; + } + + /* + * Метод должен вернуть список производителей которые + * делают и пк и ноутбуки + */ + public ArrayList selectMaker(Statement stmt) { + ArrayList ans = new ArrayList<>(); + try { + try (ResultSet resultSet = + stmt.executeQuery("select distinct maker from product p group by type")) { + while (resultSet.next()) { + ans.add(resultSet.getString(1)); + } + } + } catch (SQLException e) { + e.printStackTrace(); } - - /* - * Метод должен вернуть список id ноутов, скорость процессора - * которых выше чем 2500 - */ - - public ArrayList selectQuickLaptop(Statement stmt) { - // TODO: 16.12.2019 - return null; - } - - /* - * Метод должен вернуть список производителей которые - * делают и пк и ноутбуки - */ - public ArrayList selectMaker(Statement stmt){ - ArrayList ans = new ArrayList<>(); - // TODO: 18.02.2020 - return ans; - } - - /* - * Метод должен вернуть максимальную среди всех произодителей - * суммарную стоимость всех изделий типов ноутбук или компьютер, - * произведенных одним производителем - * Необходимо объединить таблицы продуктов ноутбуков и компьютеров - * и отгрупировать по сумме прайсов после чего выбрать максимум - * или сделать любым другим способом - */ - - public int makerWithMaxProceeds(Statement stmt){ - int result = 0; - //todo - return result; - + return ans; + } + + /* + * Метод должен вернуть максимальную среди всех произодителей + * суммарную стоимость всех изделий типов ноутбук или компьютер, + * произведенных одним производителем + * Необходимо объединить таблицы продуктов ноутбуков и компьютеров + * и отгрупировать по сумме прайсов после чего выбрать максимум + * или сделать любым другим способом + */ + + public int makerWithMaxProceeds(Statement stmt) { + int result = 0; + try { + try (ResultSet resultSet = + stmt.executeQuery( + "SELECT MAX(s)\n" + + "FROM (SELECT p.maker,\n" + + " SUM(COALESCE(k.price,COALESCE(l.price,0))) s\n" + + " FROM (SELECT DISTINCT * FROM product pp) p\n" + + " LEFT JOIN pc k\n" + + " ON k.model = p.model\n" + + " AND p.\"type\" = 'PC'\n" + + " LEFT JOIN laptop l\n" + + " ON l.model = p.model\n" + + " AND p.\"type\" = 'Laptop'\n" + + " GROUP BY p.maker)")) { + while (resultSet.next()) { + result = resultSet.getInt(1); + } + } + } catch (SQLException e) { + e.printStackTrace(); } + return result; + } } diff --git a/task2/src/test/java/DBTests.java b/task2/src/test/java/DBTests.java index 64d94e4..8b9d0ac 100644 --- a/task2/src/test/java/DBTests.java +++ b/task2/src/test/java/DBTests.java @@ -10,68 +10,68 @@ public class DBTests { - Connection con; - Statement stmt; - DBUtility util; + Connection con; + Statement stmt; + DBUtility util; - @Before - public void starter() { - try { - util = new DBUtility(); - Class.forName("org.sqlite.JDBC"); - con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Mikhail\\IdeaProjects\\Java31\\homework.db"); - stmt = con.createStatement(); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } + @Before + public void starter() { + try { + util = new DBUtility(); + Class.forName("org.sqlite.JDBC"); + con = + DriverManager.getConnection( + "jdbc:sqlite:C:\\Users\\MishinMV\\Documents\\DEV\\Java3-1\\homework.db"); + stmt = con.createStatement(); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); } + } - @After - public void closer(){ - try { - stmt.close(); - con.close(); - }catch (Exception ignored){ + @After + public void closer() { + try { + stmt.close(); + con.close(); + } catch (Exception ignored) { - } } + } - @Test - public void testTable() throws SQLException { - stmt.execute("DROP TABLE IF EXISTS Printer"); - util.createPrinterTable(con, stmt); - ResultSet res = stmt.executeQuery("SELECT * FROM Printer"); - int cnt = 0; - while (res.next())cnt++; - Assert.assertEquals(3, cnt); - } - - @Test - public void testExpensivePC(){ - ArrayList list = util.selectExpensivePC(stmt); - list.sort(Comparator.comparing(o->o)); - Assert.assertArrayEquals(new String[]{"2205", "2210"}, list.toArray()); - } + @Test + public void testTable() throws SQLException { + stmt.execute("DROP TABLE IF EXISTS Printer"); + util.createPrinterTable(con, stmt); + ResultSet res = stmt.executeQuery("SELECT * FROM Printer"); + int cnt = 0; + while (res.next()) cnt++; + Assert.assertEquals(3, cnt); + } - @Test - public void testQuickLaptop(){ - ArrayList list = util.selectQuickLaptop(stmt); - Collections.sort(list); - Assert.assertArrayEquals(new Integer[]{3, 7}, list.toArray()); - } + @Test + public void testExpensivePC() { + ArrayList list = util.selectExpensivePC(stmt); + list.sort(Comparator.comparing(o -> o)); + Assert.assertArrayEquals(new String[] {"2205", "2210"}, list.toArray()); + } - @Test - public void testMaker(){ - ArrayList list = util.selectMaker(stmt); - Collections.sort(list); - Assert.assertArrayEquals(new String[]{"Intel"}, list.toArray()); - } - - @Test - public void maxCostTest(){ - int max = util.makerWithMaxProceeds(stmt); - Assert.assertEquals(140000, max); - } + @Test + public void testQuickLaptop() { + ArrayList list = util.selectQuickLaptop(stmt); + Collections.sort(list); + Assert.assertArrayEquals(new Integer[] {3, 7}, list.toArray()); + } + @Test + public void testMaker() { + ArrayList list = util.selectMaker(stmt); + Collections.sort(list); + Assert.assertArrayEquals(new String[] {"Intel"}, list.toArray()); + } + @Test + public void maxCostTest() { + int max = util.makerWithMaxProceeds(stmt); + Assert.assertEquals(140000, max); + } } diff --git a/task2/target/classes/DBClass.class b/task2/target/classes/DBClass.class index a7506c5..29d826b 100644 Binary files a/task2/target/classes/DBClass.class and b/task2/target/classes/DBClass.class differ diff --git a/task2/target/classes/DBUtility.class b/task2/target/classes/DBUtility.class index 8e43b51..a0d0d41 100644 Binary files a/task2/target/classes/DBUtility.class and b/task2/target/classes/DBUtility.class differ diff --git a/task2/target/test-classes/DBTests.class b/task2/target/test-classes/DBTests.class index 8b582aa..69f18ea 100644 Binary files a/task2/target/test-classes/DBTests.class and b/task2/target/test-classes/DBTests.class differ diff --git a/task2/target/test-classes/HomeWorkLesson2.class b/task2/target/test-classes/HomeWorkLesson2.class index e372c08..29cb2c3 100644 Binary files a/task2/target/test-classes/HomeWorkLesson2.class and b/task2/target/test-classes/HomeWorkLesson2.class differ diff --git a/task3/pom.xml b/task3/pom.xml index fb64987..9028b48 100644 --- a/task3/pom.xml +++ b/task3/pom.xml @@ -13,8 +13,8 @@ org.apache.maven.plugins maven-compiler-plugin - 8 - 8 + 11 + 11 diff --git a/task3/src/main/java/FileUtility.java b/task3/src/main/java/FileUtility.java index 39b4c64..89defc5 100644 --- a/task3/src/main/java/FileUtility.java +++ b/task3/src/main/java/FileUtility.java @@ -1,98 +1,196 @@ import java.io.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; public class FileUtility { - /* - * Структура файла ввода: в первой строке одно целое число - N - * далее следует N целых чисел через пробел - * Метод должен отсортировать элементы с четным значением, - * а нечетные оставить на своих местах и вывести результат через пробел в файл вывода - * Пример: - * in: - * 5 - * 5 4 2 1 3 // 2 4 - * out: - * 5 2 4 1 3 - */ - - public void sortEvenElements(File in, File out) { - //TODO - try { - Scanner cin = new Scanner(in); - int n = cin.nextInt(); - int [] a = new int[n]; - LinkedList even = new LinkedList<>(); - for (int i = 0; i < n; i++) { - a[i] = cin.nextInt(); - if (a[i] % 2 == 0) { - even.add(a[i]); //O(1) - //O(n) - } - } - Collections.sort(even); - for (int i = 0; i < n; i++) { - if (a[i] % 2 == 0) { - a[i] = even.pollFirst(); //O(1) - } - } - FileWriter writer = new FileWriter(out); - for (int i = 0; i < n; i++) { - writer.write(a[i] + " "); - } - writer.close(); - } catch (IOException e) { - e.printStackTrace(); + /* + * Структура файла ввода: в первой строке одно целое число - N + * далее следует N целых чисел через пробел + * Метод должен отсортировать элементы с четным значением, + * а нечетные оставить на своих местах и вывести результат через пробел в файл вывода + * Пример: + * in: + * 5 + * 5 4 2 1 3 // 2 4 + * out: + * 5 2 4 1 3 + */ + public void sortEvenElements(File in, File out) { + String[] numbers = new String[0]; + + try (BufferedReader reader = new BufferedReader(new FileReader(in))) { + int inputSize = Integer.parseInt(reader.readLine()); // Reading 1st line + numbers = reader + .readLine() + .split(" "); // Reading second line + + // Adding even numbers to ArrayList + ArrayList evens = new ArrayList<>(); + for (int i = 0; i < inputSize; i++) { + int currentItem = Integer.parseInt(numbers[i]); + if ((currentItem % 2) == 0) { + evens.add(currentItem); + // Replacing even number with % symbol + numbers[i] = "%"; + } + } + Collections.sort(evens); // Сортируем четные числа + + int j = 0; + for (int i = 0; i < inputSize; i++) + if (numbers[i].equals("%")) { + numbers[i] = String.valueOf( + // Восстанавливаем начальный массив отсортированными четными числами + evens.get(j++)); } + } catch (IOException e) { + e.printStackTrace(); } - /* - * Генератор паролей, пароль должен отвечать требованиям: - * длина не менее 6 и не более 12, включает минимум по одному символу - * из наборов: a-z, A-Z, 0-9, {*,!,%} - * все пароли должны быть разными - * На вход метод получает файл с логинами пользователей - * Метод должен записать в файл вывода записи с логинами и паролями - * для каждого пользователя - */ + // Записываем полученный массив в файл + try (BufferedWriter writer = new BufferedWriter(new FileWriter(out))) { + for (final String number : numbers) { + writer.write(number + " "); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } - public void passwordGen(File in, File out) { - //TODO + /* + * Генератор паролей, пароль должен отвечать требованиям: + * длина не менее 6 и не более 12, включает минимум по одному символу + * из наборов: a-z, A-Z, 0-9, {*,!,%} + * все пароли должны быть разными + * На вход метод получает файл с логинами пользователей + * Метод должен записать в файл вывода записи с логинами и паролями + * для каждого пользователя + */ + public void passwordGen(File in, File out) { + HashSet passwords = new HashSet<>(); + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(in)); + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(out)) + ) { + String line; + while ((line = bufferedReader.readLine()) != null) { + while (true) { + String password = genPassword(); + // Проверяем, что такого пароля еще нет + if (!passwords.contains(password)) { + passwords.add(password); + System.out.println(line + " " + password); + bufferedWriter.write(line + " " + password + "\n"); + break; + } + } + } + } catch (IOException e) { + e.printStackTrace(); } - /* - * Метод должен дописать в переданный файл все - * записи из списка по одной записи в строке - * */ - public void appender(File file, List records) { - //SOLID - //LISKOV + } + private String genPassword() { + int passwordLength = ThreadLocalRandom + .current() + .nextInt(6, 12); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < passwordLength; i++) { + // Вызываем по одному методу + if (i % 4 == 0) { + result.append(getPasswordSymbol("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + } else if (i % 4 == 1) { + result.append(getPasswordSymbol("abcdefghijklmnopqrstuvwxyz")); + } else if (i % 4 == 2) { + result.append(getPasswordSymbol("0123456789")); + } else { + result.append(getPasswordSymbol("*!%")); + } + } + return result.toString(); + } - try (FileWriter writer = new FileWriter(file, true)) { - for(String str : records) { - writer.write(str + "\n"); - } - } catch (IOException e) { - e.printStackTrace(); - } + private char getPasswordSymbol(final String stringLine) { + char result = 0; + for (int j = 0; j < stringLine.length(); j++) { + result = stringLine.charAt(ThreadLocalRandom + .current() + .nextInt(stringLine.length())); + } + return result; + } + + + /* + * Метод должен дописать в переданный файл все + * записи из списка по одной записи в строке + * */ + public void appender(File file, List records) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) { + writer.newLine(); + for (String record : records) { + writer.write(record + "\n"); + } + } catch (IOException e) { + e.printStackTrace(); } + } - /* - * Метод возвращает список из N последних строк файла - * строки можно дополнять пробелами до длины 80 - * тогда количество символов в файле будет предсказуемо - * 10 строк это ровно 800 символов - * Изучите класс RandomAccessFile для эффективного решения данной - * задачи - * Альтернативное решение: использование очереди или стека - * */ - public List getNString(String pathToFile, int n) { - //TODO - // \n \r, \n - return null; + /* + * Метод возвращает список из N последних строк файла + * строки можно дополнять пробелами до длины 80 + * тогда количество символов в файле будет предсказуемо + * 10 строк это ровно 800 символов + * Изучите класс RandomAccessFile для эффективного решения данной + * задачи + * Альтернативное решение: использование очереди или стека + * */ + public List getNString(String pathToFile, int n) { + List tmpResult = new ArrayList<>(); + try (RandomAccessFile randomAccessFile = new RandomAccessFile(pathToFile, "r")) { + // lines number + int lines = 0; + // get file length + long length = randomAccessFile.length(); + // сюда будем считывать символы строк + StringBuilder builder = new StringBuilder(); + // ставим указатель на последний символ файла + length--; + // seek to the end of file + randomAccessFile.seek(length); + // считываем строки с конца + for (long i = length; i >= 0; --i) { + randomAccessFile.seek(i); + // читаем символ + char c = (char) randomAccessFile.read(); + // добавляем символ в стрингбилдер + builder.append(c); + // Если новая строка и длина строки больше 1 - то добавляем строку в конечный результат + if (c == '\n' && builder.length() > 1) { + // реверсируем строку + builder = builder.reverse(); + // добавляем строку + tmpResult.add(String.valueOf(builder)); + lines++; + // обнуляем стрингбилдер + builder = new StringBuilder(); + // если прочитали нужное число строк - прерываем цикл + if (lines == n) break; + } + } + } catch (IOException e) { + e.printStackTrace(); } + // Реверсируем список, т.к. читаем снизу вверх + Collections.reverse(tmpResult); + return tmpResult; + } } diff --git a/task3/src/main/java/classwork/FileSystem.java b/task3/src/main/java/classwork/FileSystem.java index 3f3052c..fd135cd 100644 --- a/task3/src/main/java/classwork/FileSystem.java +++ b/task3/src/main/java/classwork/FileSystem.java @@ -1,20 +1,12 @@ package classwork; -import jdk.management.resource.internal.inst.FileInputStreamRMHooks; - -import java.io.*; -import java.lang.reflect.Field; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Scanner; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; public class FileSystem { - static String path = "C:\\Users\\Mikhail\\IdeaProjects\\Java31\\task3\\src\\main\\java\\classwork"; + static String path = "D:\\Projects\\Java3-1\\task3\\src\\main\\resources"; public static void main(String[] args) throws IOException, ClassNotFoundException { //System.out.println(Arrays.toString(File.listRoots())); File file = new File(path + "1.txt"); diff --git a/task3/src/main/resources/append.txt b/task3/src/main/resources/append.txt index 3b7b424..5f5e8d2 100644 --- a/task3/src/main/resources/append.txt +++ b/task3/src/main/resources/append.txt @@ -1,10 +1,3 @@ str1 str2 -str3 -str4 -str5 -str6 -str7 -str8 -str9 -str10 +str3 \ No newline at end of file diff --git a/task3/src/main/resources/arrayout.txt b/task3/src/main/resources/arrayout.txt deleted file mode 100644 index 8cb9809..0000000 --- a/task3/src/main/resources/arrayout.txt +++ /dev/null @@ -1 +0,0 @@ -4 8 5 7 10 9 7 12 11 14 \ No newline at end of file diff --git a/task3/src/main/resources/pass.txt b/task3/src/main/resources/pass.txt deleted file mode 100644 index 8b13789..0000000 --- a/task3/src/main/resources/pass.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/task3/src/test/java/FileTests.java b/task3/src/test/java/FileTests.java index afb75fe..79b51ef 100644 --- a/task3/src/test/java/FileTests.java +++ b/task3/src/test/java/FileTests.java @@ -5,108 +5,113 @@ import java.io.File; import java.io.FileNotFoundException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Scanner; @DisplayName("Home work 3") public class FileTests { - FileUtility util; - String pathToResource; + FileUtility util; + String pathToResource; - @Before - public void starter(){ - //change your path - pathToResource = "C:\\Users\\Mikhail\\IdeaProjects\\Java31\\task3\\src\\main\\resources\\"; - util = new FileUtility(); - } + @Before + public void starter() { + //change your path + pathToResource = "D:\\Projects\\Java3-1\\task3\\src\\main\\resources\\"; + util = new FileUtility(); + } - @Test - public void testSort(){ - File input = new File(pathToResource + "array.txt"); - File output = new File(pathToResource + "arrayout.txt"); - util.sortEvenElements(input, output); - int [] arr = new int[]{4, 8, 5, 7, 10, 9, 7, 12, 11, 14}; - try { - Scanner in = new Scanner(output); - int pos = 0; - while (in.hasNext()){ - int x = in.nextInt(); - Assert.assertEquals(arr[pos++], x); - } - Assert.assertEquals(10, pos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } + @Test + public void testSort() { + File input = new File(pathToResource + "array.txt"); + File output = new File(pathToResource + "arrayout.txt"); + util.sortEvenElements(input, output); + int[] arr = new int[]{4, 8, 5, 7, 10, 9, 7, 12, 11, 14}; + try { + Scanner in = new Scanner(output); + int pos = 0; + while (in.hasNext()) { + int x = in.nextInt(); + Assert.assertEquals(arr[pos++], x); + } + Assert.assertEquals(10, pos); + } catch (FileNotFoundException e) { + e.printStackTrace(); } + } - private boolean check(String pass){ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - for (int i = 0; i < pass.length(); i++) { - if(pass.charAt(i) >= 'a' && pass.charAt(i) <= 'z'){ - c1++; - } - if(pass.charAt(i) >= 'A' && pass.charAt(i) <= 'Z'){ - c2++; - } - if(pass.charAt(i) >= '0' && pass.charAt(i) <= '9'){ - c3++; - } - if(pass.charAt(i) == '*' || pass.charAt(i) == '!' || - pass.charAt(i) == '%'){ - c4++; - } - } - return pass.length() > 5 && pass.length() < 13 && c1 > 0 && c2 > 0 && c3 > 0 && c4 > 0; + @Test + public void testPassGen() { + File input = new File(pathToResource + "login.txt"); + File output = new File(pathToResource + "pass.txt"); + util.passwordGen(input, output); + HashSet set = new HashSet<>(); + try { + Scanner in = new Scanner(output); + while (in.hasNextLine()) { + String pass = in.nextLine() + .split(" ")[1]; + Assert.assertTrue(check(pass)); + set.add(pass); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); } + Assert.assertEquals(7, set.size()); + } - @Test - public void testPassGen(){ - File input = new File(pathToResource + "login.txt"); - File output = new File(pathToResource + "pass.txt"); - util.passwordGen(input, output); - HashSet set = new HashSet<>(); - try { - Scanner in = new Scanner(output); - while (in.hasNextLine()){ - String pass = in.nextLine().split(" ")[1]; - Assert.assertTrue(check(pass)); - set.add(pass); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - Assert.assertEquals(7, set.size()); + private boolean check(String pass) { + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + for (int i = 0; i < pass.length(); i++) { + if (pass.charAt(i) >= 'a' && pass.charAt(i) <= 'z') { + c1++; + } + if (pass.charAt(i) >= 'A' && pass.charAt(i) <= 'Z') { + c2++; + } + if (pass.charAt(i) >= '0' && pass.charAt(i) <= '9') { + c3++; + } + if (pass.charAt(i) == '*' || pass.charAt(i) == '!' || + pass.charAt(i) == '%') { + c4++; + } } + return pass.length() > 5 && pass.length() < 13 && c1 > 0 && c2 > 0 && c3 > 0 && c4 > 0; + } - @Test - public void testAppend(){ - File file = new File(pathToResource + "append.txt"); - ArrayList list = new ArrayList<>(); - for (int i = 4; i < 11; i++) { - list.add("str" + i); - } - util.appender(file, list); - try { - Scanner in = new Scanner(file); - int pos = 1; - while (in.hasNextLine()){ - String line = in.nextLine(); - Assert.assertEquals(line, "str" + pos); - pos++; - } - Assert.assertEquals(11, pos); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } + @Test + public void testAppend() { + File file = new File(pathToResource + "append.txt"); + ArrayList list = new ArrayList<>(); + for (int i = 4; i < 11; i++) { + list.add("str" + i); + } + util.appender(file, list); + try { + Scanner in = new Scanner(file); + int pos = 1; + while (in.hasNextLine()) { + String line = in.nextLine(); + Assert.assertEquals(line, "str" + pos); + pos++; + } + Assert.assertEquals(11, pos); + } catch (FileNotFoundException e) { + e.printStackTrace(); } + } - @Test - public void testNLines(){ - List list = - util.getNString(pathToResource + "file.txt", 100); - for (int i = 0; i < 100; i++) { - Assert.assertEquals("Oleg message " + (i + 900), - list.get(i).trim()); - } + @Test + public void testNLines() { + List list = + util.getNString(pathToResource + "file.txt", 100); + for (int i = 0; i < 100; i++) { + Assert.assertEquals("Oleg message " + (i + 900), + list.get(i) + .trim()); } -} + } +} \ No newline at end of file diff --git a/task3/task3.iml b/task3/task3.iml index 2a3c5ba..ef2de46 100644 --- a/task3/task3.iml +++ b/task3/task3.iml @@ -1,6 +1,6 @@ - + @@ -13,12 +13,12 @@ - - + + - - - + + + diff --git a/task4/task4.iml b/task4/task4.iml index 2394831..d140331 100644 --- a/task4/task4.iml +++ b/task4/task4.iml @@ -11,12 +11,12 @@ - - + + - - - + + +