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
Original file line number Diff line number Diff line change
@@ -1,60 +1,92 @@
package com.epam.izh.rd.online.repository;
package com.epam.izh.rd.online.repository;import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.stream.Collectors;

public class SimpleFileRepository implements FileRepository {

/**
* Метод рекурсивно подсчитывает количество файлов в директории
*
* @param path путь до директори
* @return файлов, в том числе скрытых
*/

@Override
public long countFilesInDirectory(String path) {
return 0;
long c = 0;
File dir = new File("src/main/resources/" + path);
File[] dirs = dir.listFiles();
if (dirs != null) {
for (File file : dirs) {
if (file.isFile()) {
c++;
}
if (file.isDirectory()) {
c += countFilesInDirectory(path + "/" + file.getName());
}
}
}
return c;
}

/**
* Метод рекурсивно подсчитывает количество папок в директории, считая корень
*
* @param path путь до директории
* @return число папок
*/

@Override
public long countDirsInDirectory(String path) {
return 0;
long c = 1;
File dir = new File("src/main/resources/" + path);
File[] dirs = dir.listFiles();
if (dirs != null) {
for (File file : dirs) {
if (file.isDirectory()) {
c++;
}
if (file.isDirectory()) {
c += countDirsInDirectory(path + "/" + file.getName())-1;
}
}
}
return c;
}

/**
* Метод копирует все файлы с расширением .txt
*
* @param from путь откуда
* @param to путь куда
*/

@Override
public void copyTXTFiles(String from, String to) {
return;
File dirFrom = new File(from);
File dirTo = new File(to);
if (!dirTo.getParentFile().exists()) {
dirTo.getParentFile().mkdirs();
}
try {
Files.copy(dirFrom.getAbsoluteFile().toPath(), dirTo.getAbsoluteFile().toPath());
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Метод создает файл на диске с расширением txt
*
* @param path путь до нового файла
* @param name имя файла
* @return был ли создан файл
*/

@Override
public boolean createFile(String path, String name) {
public boolean createFile(String path, String name) {
String targetFolder = "target/classes/";
File dir = new File(targetFolder + path);
dir.mkdir();
File file = new File(dir.getPath() + File.separator + name);
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

/**
* Метод считывает тело файла .txt из папки src/main/resources
*
* @param fileName имя файла
* @return контент
*/

@Override
public String readFileFromResources(String fileName) {
URL resource = getClass().getClassLoader().getResource(fileName);
File file = new File(resource.getFile());
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
return in.lines().collect(Collectors.joining());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,34 @@

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;

import static java.lang.StrictMath.sqrt;

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;
return new BigDecimal(a).divide(new BigDecimal(b), range, RoundingMode.HALF_UP);
}

/**
* Метод находит простое число по номеру
*
* @param range номер числа, считая с числа 2
* @return простое число
*/

@Override
public BigInteger getPrimaryNumber(int range) {
return null;
int i = 0;
BigInteger number = new BigInteger("1");
while (true) {
if (number.isProbablePrime(range)) {
if (i == range) {
return number;
}
i++;
}
number = number.add(new BigInteger("1"));
}
}


}
51 changes: 14 additions & 37 deletions src/main/java/com/epam/izh/rd/online/service/SimpleDateService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,40 @@

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;

public class SimpleDateService implements DateService {

/**
* Метод парсит дату в строку
*
* @param localDate дата
* @return строка с форматом день-месяц-год(01-01-1970)
*/
@Override
public String parseDate(LocalDate localDate) {
return null;
return localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
}

/**
* Метод парсит строку в дату
*
* @param string строка в формате год-месяц-день часы:минуты (1970-01-01 00:00)
* @return дата и время
*/
@Override
public LocalDateTime parseString(String string) {
return null;
return LocalDateTime.parse(string, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}

/**
* Метод конвертирует дату в строку с заданным форматом
*
* @param localDate исходная дата
* @param formatter формат даты
* @return полученная строка
*/
@Override
public String convertToCustomFormat(LocalDate localDate, DateTimeFormatter formatter) {
return null;
return localDate.format(formatter);
}

/**
* Метод получает следующий високосный год
*
* @return високосный год
*/
@Override
public long getNextLeapYear() {
return 0;
int y = Year.now().getValue();
while (!Year.of(y).isLeap()) {
y++;
}
return y;
}

/**
* Метод считает число секунд в заданном году
*
* @return число секунд
*/
@Override
public long getSecondsInYear(int year) {
return 0;
if (Year.isLeap(year)) {
return LocalDate.now().lengthOfYear() * 24 * 3600 + 24 * 3600;
}
return LocalDate.now().lengthOfYear() * 24 * 3600;
}


}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,56 @@
package com.epam.izh.rd.online.service;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleRegExpService implements RegExpService {

/**
* Метод должен читать файл sensitive_data.txt (из директории resources) и маскировать в нем конфиденциальную информацию.
* Номер счета должен содержать только первые 4 и последние 4 цифры (1234 **** **** 5678). Метод должен содержать регулярное
* выражение для поиска счета.
*
* @return обработанный текст
*/

@Override
public String maskSensitiveData() {
return null;
File file = new File("src/main/resources/sensitive_data.txt");
String text = "";
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
text = reader.readLine();
}catch (IOException e) {
e.printStackTrace();
}
String regex = "\\d{4}\\s\\d{4}\\s\\d{4}\\s\\d{4}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String cardNumber;
String[] numberParts;
while (matcher.find()) {
cardNumber = matcher.group();
numberParts = cardNumber.split(" ");
text = text.replaceAll(cardNumber,numberParts[0] + " **** **** " + numberParts[3]);
}
return text;
}

/**
* Метод должен считыввать файл sensitive_data.txt (из директории resources) и заменять плейсхолдер ${payment_amount} и ${balance} на заданные числа. Метод должен
* содержать регулярное выражение для поиска плейсхолдеров
*
* @return обработанный текст
*/

@Override
public String replacePlaceholders(double paymentAmount, double balance) {
return null;
String text = "";
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/sensitive_data.txt"))) {
text = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Pattern pattern = Pattern.compile("\\$\\{.*?}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
if (matcher.group().equals("${payment_amount}")) {
text = text.replaceAll("\\$\\{payment_amount}", "" + (int)paymentAmount);
} else if (matcher.group().equals("${balance}")) {
text = text.replaceAll("\\$\\{balance}", "" + (int)balance);
}
}
return text;
}
}
Loading