diff --git a/java-data-handling-template.iml b/java-data-handling-template.iml new file mode 100644 index 00000000..5e9ffdc5 --- /dev/null +++ b/java-data-handling-template.iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleFileRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleFileRepository.java index 1783b845..59a2795f 100644 --- a/src/main/java/com/epam/izh/rd/online/repository/SimpleFileRepository.java +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleFileRepository.java @@ -1,5 +1,9 @@ package com.epam.izh.rd.online.repository; +import java.io.File; +import java.io.IOException; +import java.nio.file.*; + public class SimpleFileRepository implements FileRepository { /** @@ -10,7 +14,16 @@ public class SimpleFileRepository implements FileRepository { */ @Override public long countFilesInDirectory(String path) { - return 0; + long count = 0; + try { + Files.walk(Paths.get(path)) + .filter(Files::isRegularFile) + .count(); + } catch (IOException e) { + e.printStackTrace(); + return 0; + } + return count; } /** @@ -21,7 +34,16 @@ public long countFilesInDirectory(String path) { */ @Override public long countDirsInDirectory(String path) { - return 0; + long count = 0; + try { + Files.walk(Paths.get(path)) + .filter(p -> p.toFile().isDirectory()) + .count(); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + return count; } /** @@ -32,7 +54,22 @@ public long countDirsInDirectory(String path) { */ @Override public void copyTXTFiles(String from, String to) { - return; + Path fromPath = Paths.get(from).normalize(); + Path toPath = Paths.get(to).normalize(); + if (toPath.getParent() != null) { + if (fromPath.endsWith(".txt") && (Files.notExists(toPath.getParent()))) { + try { + Files.createDirectories(toPath.getParent()); + } catch (IOException e) { + e.printStackTrace(); + } + try { + Files.copy(fromPath, toPath); + } catch (IOException e) { + e.printStackTrace(); + } + } + } } /** @@ -44,9 +81,47 @@ public void copyTXTFiles(String from, String to) { */ @Override public boolean createFile(String path, String name) { - return false; + boolean isCreateDir = false; + boolean isCreateFile = false; + Path dirPath = Paths.get(System.getProperty("user.dir") + File.separator + path).normalize(); + Path filePath = Paths.get(dirPath + File.separator + name).normalize(); + + if (Files.notExists(dirPath)) { + try { + Files.createDirectories(dirPath); + isCreateDir = Files.exists(dirPath); + } catch (IOException e) { + isCreateDir = Files.exists(dirPath); + e.printStackTrace(); + } + if (Files.notExists(filePath)) { + try { + Files.createFile(filePath); + isCreateFile = Files.exists(filePath); + } catch (IOException e) { + isCreateFile = Files.exists(filePath); + e.printStackTrace(); + } + } + + } else if (Files.exists(dirPath) && Files.notExists(filePath)) { + isCreateDir = Files.exists(dirPath); + try { + Files.createFile(filePath); + isCreateFile = Files.exists(filePath); + } catch (IOException e) { + isCreateFile = Files.exists(filePath); + e.printStackTrace(); + } + + } else { + isCreateDir = Files.exists(dirPath); + isCreateFile = Files.exists(filePath); + } + return (isCreateDir && isCreateFile); } + /** * Метод считывает тело файла .txt из папки src/main/resources * @@ -55,6 +130,13 @@ public boolean createFile(String path, String name) { */ @Override public String readFileFromResources(String fileName) { - return null; + Path path = Paths.get("src/main/resources" + File.separator + fileName); + String read = ""; + try { + read = Files.readAllLines(path).get(0); + } catch (IOException e) { + e.printStackTrace(); + } + return read; } } diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleBigNumbersService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleBigNumbersService.java index a94c7bba..22028eaa 100644 --- a/src/main/java/com/epam/izh/rd/online/service/SimpleBigNumbersService.java +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleBigNumbersService.java @@ -8,12 +8,15 @@ public class SimpleBigNumbersService implements BigNumbersService { /** * Метод делит первое число на второе с заданной точностью * Например 1/3 с точностью 2 = 0.33 + * * @param range точность * @return результат */ @Override public BigDecimal getPrecisionNumber(int a, int b, int range) { - return null; + BigDecimal aa = new BigDecimal(a); + BigDecimal bb = new BigDecimal(b); + return aa.divide(bb, range, BigDecimal.ROUND_HALF_UP); } /** @@ -24,6 +27,10 @@ public BigDecimal getPrecisionNumber(int a, int b, int range) { */ @Override public BigInteger getPrimaryNumber(int range) { - return null; + BigInteger temp = new BigInteger("2"); + for (int i = 0; i < range; i++) { + temp = temp.nextProbablePrime(); + } + return temp; } } diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleDateService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleDateService.java index 70d64dfd..f370d51c 100644 --- a/src/main/java/com/epam/izh/rd/online/service/SimpleDateService.java +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleDateService.java @@ -2,7 +2,9 @@ import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.Year; import java.time.format.DateTimeFormatter; +import java.util.concurrent.TimeUnit; public class SimpleDateService implements DateService { @@ -14,7 +16,9 @@ public class SimpleDateService implements DateService { */ @Override public String parseDate(LocalDate localDate) { - return null; + DateTimeFormatter dmy = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + String date = localDate.format(dmy); + return date; } /** @@ -25,7 +29,9 @@ public String parseDate(LocalDate localDate) { */ @Override public LocalDateTime parseString(String string) { - return null; + DateTimeFormatter yMdhm = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm"); + LocalDateTime date = LocalDate.parse(string, yMdhm).atStartOfDay(); + return date; } /** @@ -37,7 +43,7 @@ public LocalDateTime parseString(String string) { */ @Override public String convertToCustomFormat(LocalDate localDate, DateTimeFormatter formatter) { - return null; + return localDate.format(formatter); } /** @@ -47,7 +53,12 @@ public String convertToCustomFormat(LocalDate localDate, DateTimeFormatter forma */ @Override public long getNextLeapYear() { - return 0; + long yearForCheck = Year.now().getValue(); + do { + yearForCheck++; + } while (!Year.isLeap(yearForCheck)); + + return yearForCheck; } /** @@ -57,7 +68,8 @@ public long getNextLeapYear() { */ @Override public long getSecondsInYear(int year) { - return 0; + long secondsInYear = TimeUnit.DAYS.toSeconds(Year.of(year).length()); + return secondsInYear; } diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleRegExpService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleRegExpService.java index b6eff56b..0357e4ef 100644 --- a/src/main/java/com/epam/izh/rd/online/service/SimpleRegExpService.java +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleRegExpService.java @@ -1,5 +1,13 @@ package com.epam.izh.rd.online.service; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class SimpleRegExpService implements RegExpService { /** @@ -11,7 +19,20 @@ public class SimpleRegExpService implements RegExpService { */ @Override public String maskSensitiveData() { - return null; + Pattern paymentAmountAndBalance = Pattern.compile("(?<=\\d{4}\\s)(\\d{4}\\s\\d{4})(?=\\s\\d{4})"); + Path sensitivePath = Paths.get("src" + File.separator + "main" + File.separator + "resources" + File.separator + "sensitive_data.txt"); + String read = ""; + try { + read = Files.readAllLines(sensitivePath).get(0); + } catch (IOException e) { + e.printStackTrace(); + } + Matcher source = paymentAmountAndBalance.matcher(read); + boolean isMatch = source.find(); + if (isMatch) { + read = read.replaceAll(paymentAmountAndBalance.pattern().toString(), "\\*\\*\\*\\* \\*\\*\\*\\*"); + } + return read; } /** @@ -22,6 +43,24 @@ public String maskSensitiveData() { */ @Override public String replacePlaceholders(double paymentAmount, double balance) { - return null; + int roundPaymentAmount = (int) Math.round(paymentAmount); + int roundBalance = (int) Math.round(balance); + Pattern paymentAmountAndBalance = Pattern.compile("\\$\\{payment_amount}|\\$\\{balance}"); + String stringPaymentAmount = String.valueOf(roundPaymentAmount); + String stringBalance = String.valueOf(roundBalance); + Path sensitivePath = Paths.get("src" + File.separator + "main" + File.separator + "resources" + File.separator + "sensitive_data.txt"); + String read = ""; + try { + read = Files.readAllLines(sensitivePath).get(0); + } catch (IOException e) { + e.printStackTrace(); + } + Matcher source = paymentAmountAndBalance.matcher(read); + boolean isMatch = source.find(); + if (isMatch) { + read = read.replaceAll("\\$\\{payment_amount}", stringPaymentAmount) + .replaceAll("\\$\\{balance}", stringBalance); + } + return read; } } diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleTextService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleTextService.java index 68951fbe..08c214d0 100644 --- a/src/main/java/com/epam/izh/rd/online/service/SimpleTextService.java +++ b/src/main/java/com/epam/izh/rd/online/service/SimpleTextService.java @@ -4,61 +4,95 @@ public class SimpleTextService implements TextService { /** * Реализовать функционал удаления строки из другой строки. - * + *

* Например для базовой строки "Hello, hello, hello, how low?" и строки для удаления ", he" * метод вернет "Hellollollo, how low?" * - * @param base - базовая строка с текстом + * @param base - базовая строка с текстом * @param remove - строка которую необходимо удалить */ @Override public String removeString(String base, String remove) { - return null; //TODO + return base.replaceAll(remove, ""); //TODO } /** * Реализовать функционал проверки на то, что строка заканчивается знаком вопроса. - * + *

* Например для строки "Hello, hello, hello, how low?" метод вернет true * Например для строки "Hello, hello, hello!" метод вернет false */ @Override public boolean isQuestionString(String text) { - return false; //TODO + return text.endsWith("?"); //TODO } /** * Реализовать функционал соединения переданных строк. - * + *

* Например для параметров {"Smells", " ", "Like", " ", "Teen", " ", "Spirit"} * метод вернет "Smells Like Teen Spirit" */ @Override public String concatenate(String... elements) { - return null; //TODO + String temp = elements[0]; + for (int i = 1; i < elements.length; i++) { + temp = temp.concat(elements[i]); + } + return temp; //TODO } /** * Реализовать функционал изменения регистра в вид лесенки. * Возвращаемый текст должен начинаться с прописного регистра. - * + *

* Например для строки "Load Up On Guns And Bring Your Friends" * метод вернет "lOaD Up oN GuNs aNd bRiNg yOuR FrIeNdS". */ @Override public String toJumpCase(String text) { - return null; //TODO + + if (text.length() == 0 || text.equals(null)) { + return ""; + } + + text = text.toLowerCase(); + String tempS = String.valueOf(text.toLowerCase().charAt(0)); + for (int i = 1; i < text.length(); i++) { + if (i % 2 != 0) { + tempS += text.toUpperCase().charAt(i); + } else { + tempS += text.charAt(i); + } + } + return tempS; //TODO } /** * Метод определяет, является ли строка палиндромом. - * + *

* Палиндром - строка, которая одинаково читается слева направо и справа налево. - * + *

* Например для строки "а роза упала на лапу Азора" вернется true, а для "я не палиндром" false */ @Override public boolean isPalindrome(String string) { - return false; //TODO + if (string.length() == 0 || string.equals(null)) { + return false; + } + boolean isPalindrome = false; + final String tempS = string.replaceAll("\\s+", "").toLowerCase(); + char[] chArr = tempS.toCharArray(); + int count = 0; + for (int i = chArr.length - 1; i >= 0; i--) { + if (chArr[i] == tempS.charAt((tempS.length() - 1) - i)) { + count++; + continue; + } else { + return false; + } + } + isPalindrome = count == tempS.length(); + return isPalindrome; //TODO } } diff --git a/src/main/resources/sensitive_data_.txt b/src/main/resources/sensitive_data_.txt new file mode 100644 index 00000000..4041aa51 --- /dev/null +++ b/src/main/resources/sensitive_data_.txt @@ -0,0 +1 @@ +Вчера вечером со счета номер 4301 0234 2145 2140 был совершен перевод на счет 5042 2012 0532 2043 в размере ${payment_amount} рублей. На счету осталось ${balance} рублей diff --git a/testDirCreateFile/newFile.txt b/testDirCreateFile/newFile.txt new file mode 100644 index 00000000..e69de29b