diff --git a/README.md b/README.md index 5d686e9f..34e04d76 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,17 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Antufiev Semen* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | - +| HW1 | [Solution_1](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2_1 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_2/pyramid_printer) | The app that reads input arguments and prints pyramid| +| HW2_2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_2/traffic_light) | The app that reads input arguments and prints color of traffic light now| +| HW2_3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_2/random_chars_table) | The app that reads input arguments and prints table with random charset| +| HW3 | [Immutable_class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_3) | Example of immutable class +| HW4_1 | [Custon_anotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_4/custom_annotation) | Custom annotation and handler +| HW4_2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_4/singleton) | Example of singleton class +| HW4_3 | [Custom_file_reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SemenAntufiev/src/main/java/homework_4/custom_file_reader) | Work with file readers [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[codingbat](https://codingbat.com/done?user=alexantufiev@gmail.com&tag=8698341536) diff --git a/build.gradle b/build.gradle index b91dc843..386586ba 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,10 @@ repositories { } dependencies { + implementation 'org.junit.jupiter:junit-jupiter:5.4.2' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.20' } test { diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..a44f167b 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -3,7 +3,13 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello homework!"); - } + for (String arg : args) { + if (arg.equals("error")) { + System.out.println("\u001B[41m" + "Alarm!" + "\u001B[0m"); + break; + } + System.out.println(arg + " : " + arg.length() + " letters"); + } + } } diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..15409cef --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,11 @@ +package homework_2.pyramid_printer; + +public class Main { + + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + pyramidPrinter.run(); + } + + +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..b9d8f221 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,30 @@ +package homework_2.pyramid_printer; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class PyramidPrinter { + + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + Scanner scanner = new Scanner(System.in); + String sizeAsString = scanner.nextLine(); + + if (isNumber(sizeAsString)) { + System.out.println(ERROR_MESSAGE); + return; + } + int size = Integer.parseInt(sizeAsString); + for (int i = 0; i < size; i++) { + for (int j = 0; j <= i; j++) { + System.out.print("*"); + } + System.out.println(); + } + } + + private boolean isNumber(String str) { + return !Pattern.matches( "[0-9]+", str); + } +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..e359a82c --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,9 @@ +package homework_2.random_chars_table; + +public class Main { + + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..b592032a --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,56 @@ +package homework_2.random_chars_table; + +import java.util.Random; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class RandomCharsTable { + public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public void run() { + Scanner scanner = new Scanner(System.in); + String[] params = new String[3]; + for (int i = 0; i < params.length; i++) { + params[i] = scanner.next(); + } + if (isNumber(params[0]) || isNumber(params[1])) { + System.out.println(ERROR_MESSAGE); + return; + } + int rows = Integer.parseInt(params[0]); + int columns = Integer.parseInt(params[1]); + if (rows == 0 || columns == 0) { + return; + } + if (rows < 0 || columns < 0) { + System.out.println(ERROR_MESSAGE); + return; + } + String strategy = params[2]; + int strategyMod; + if (strategy.equals("even")) { + strategyMod = 0; + } else if (strategy.equals("odd")){ + strategyMod = 1; + } else { + System.out.println(ERROR_MESSAGE); + return; + } + StringBuilder result = new StringBuilder(strategy + " letters - "); + for (int i = 0; i < rows; i++) { + System.out.print("| "); + for (int j = 0; j < columns; j++) { + char letter = (char) (65 + new Random().nextInt(26)); + System.out.print(letter + " | "); + if (letter % 2 == strategyMod) { + result.append(letter).append(", "); + } + } + System.out.println(); + } + System.out.println(result.deleteCharAt(result.length() - 2)); + } + + private boolean isNumber(String str) { + return !Pattern.matches( "[0-9]+", str); + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..747b3666 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,11 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + trafficLight.run(); + } + + +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..60e3a25f --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,44 @@ +package homework_2.traffic_light; + +import java.time.Instant; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class TrafficLight { + + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String DAY_OVER = "The day is over"; + + public void run() { + Scanner scanner = new Scanner(System.in); + String secondsAsString = scanner.next(); + if (isNumber(secondsAsString)) { + System.out.println(ERROR_MESSAGE); + return; + } + long seconds = Long.parseLong(secondsAsString); + if (seconds < 0) { + System.out.println(ERROR_MESSAGE); + return; + } + if (seconds > 86399) { + System.out.println(DAY_OVER); + return; + } + Instant instant = Instant.ofEpochSecond(seconds); + String fullTime = instant.toString(); + int size = fullTime.length(); + int onlySeconds = Integer.parseInt(fullTime.substring(size - 3, size - 1)); + if (onlySeconds >= 0 && onlySeconds < 35) { + System.out.println("Green"); + } else if (onlySeconds >= 40 && onlySeconds < 55) { + System.out.println("Red"); + } else { + System.out.println("Yellow"); + } + } + + private boolean isNumber(String str) { + return !Pattern.matches( "[0-9]+", str); + } +} diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..ff59afa1 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,80 @@ +package homework_3; + + +/* +The class must be declared as final +Data members in the class must be declared as private +Data members in the class must be declared as final +A parameterized constructor should initialize all the fields performing a deep copy +Deep Copy of objects should be performed in the getter methods +No setters + */ + + +import java.util.Objects; + +public final class ImmutableClass { + + private final int age; + + private final int high; + + private final int weight; + + private final String name; + + public ImmutableClass(int age, int high, int weight, String name) { + this.age = age; + this.high = high; + this.weight = weight; + this.name = name; + } + + public ImmutableClass(int weight, int high) { + this.high = high; + this.weight = weight; + this.age = 10; + this.name = "Some person"; + } + + public int getAge() { + return age; + } + + public int getHigh() { + return high; + } + + public int getWeight() { + return weight; + } + + public String getName() { + return name; + } + + public ImmutableClass changeWeightAndHigh(int weight, int high) { + return new ImmutableClass(weight, high); + } + + public ImmutableClass changeName(String name) { + return new ImmutableClass(this.age, this.high, this.weight, name); + } + + public ImmutableClass changeAge(int age) { + return new ImmutableClass(age, this.high, this.weight, this.name); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ImmutableClass)) return false; + ImmutableClass that = (ImmutableClass) o; + return age == that.age && high == that.high && weight == that.weight && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(age, high, weight, name); + } +} diff --git a/src/main/java/homework_4/custom_annotation/DefaulValueImpl.java b/src/main/java/homework_4/custom_annotation/DefaulValueImpl.java new file mode 100644 index 00000000..d32b99e8 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/DefaulValueImpl.java @@ -0,0 +1,72 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class DefaulValueImpl { + + public static void insetDefaultValue(Object object) throws IllegalAccessException, InvocationTargetException { + setDefaultValueToFields(object, object.getClass()); + setDefaultValueToMethods(object, object.getClass()); + + + } + + private static void setDefaultValueToMethods(Object object, Class clazz) throws InvocationTargetException, IllegalAccessException { + List collectPrivateMethods = Arrays.stream(clazz.getDeclaredMethods()) + .filter((o) -> o.isAnnotationPresent(DefaultValue.class)) + .collect(Collectors.toList()); + setDefaultValueMethods(collectPrivateMethods, clazz, object); + } + + private static void setDefaultValueToFields(Object object, Class clazz) throws IllegalAccessException { + List collectPublic = Arrays.stream(clazz.getFields()) + .filter((o) -> o.isAnnotationPresent(DefaultValue.class)) + .collect(Collectors.toList()); + getDefaultFields(collectPublic, clazz, object); + + List collectPrivate = Arrays.stream(clazz.getDeclaredFields()) + .filter((o) -> o.isAnnotationPresent(DefaultValue.class)) + .collect(Collectors.toList()); + getDefaultFields(collectPrivate, clazz, object); + + } + + private static void setDefaultValueMethods(List collectMethods, Class clazz, Object object) throws InvocationTargetException, IllegalAccessException { + for (Method method : collectMethods) { + DefaultValue annotation = method.getAnnotation(DefaultValue.class); + String value = annotation.value(); + Class type = method.getParameterTypes()[0]; + method.setAccessible(true); + if (type == Integer.class || type == int.class) { + method.invoke(object, Integer.parseInt(value)); + } else if (type == Double.class || type == double.class) { + method.invoke(object, Double.parseDouble(value)); + } else { + method.invoke(object, value); + } + } + } + + private static void getDefaultFields(List collect, Class clazz, Object object) throws IllegalAccessException { + for (Field field : collect) { + DefaultValue annotation = field.getAnnotation(DefaultValue.class); + String value = annotation.value(); + Class type = field.getType(); + field.setAccessible(true); + if (type == Integer.class || type == int.class) { + if (field.get(object) == null || field.get(object).equals(0)) + field.set(object, Integer.parseInt(value)); + } else if (type == Double.class || type == double.class) { + if (field.get(object) == null || field.get(object).equals(0.0)) + field.set(object, Double.parseDouble(value)); + } else { + if (field.get(object) == null || field.get(object).equals("")) field.set(object, value); + } + } + } +} diff --git a/src/main/java/homework_4/custom_annotation/DefaultValue.java b/src/main/java/homework_4/custom_annotation/DefaultValue.java new file mode 100644 index 00000000..5325a90f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/DefaultValue.java @@ -0,0 +1,15 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.FIELD}) +public @interface DefaultValue { + String value(); + +} diff --git a/src/main/java/homework_4/custom_annotation/Main.java b/src/main/java/homework_4/custom_annotation/Main.java new file mode 100644 index 00000000..87136bee --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,60 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.InvocationTargetException; + +public class Main { + + public static void main(String[] args) throws IllegalAccessException, InvocationTargetException { + Cat cat = new Cat(); + DefaulValueImpl.insetDefaultValue(cat); + } +} + +class Cat { + @DefaultValue("1") + private int integer; + @DefaultValue("1.0") + private Double aDouble; + @DefaultValue("awdawd") + private String string; + + + public Cat(Integer integer, Double aDouble, String string) { + this.integer = integer; + this.aDouble = aDouble; + this.string = string; + } + + public Cat() { + } + + @DefaultValue("15") + public int method(int i) { + System.out.println(i); + return i; + } + + @DefaultValue("awdawd") + private String method2(String i) { + System.out.println(i); + return i; + } + + @DefaultValue("15.0") + protected Double method(Double i) { + System.out.println(i); + return i; + } + + public Integer getInteger() { + return integer; + } + + public Double getaDouble() { + return aDouble; + } + + public String getString() { + return string; + } +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..980d97f7 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,56 @@ +package homework_4.custom_file_reader; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Scanner; +import java.util.stream.Stream; + +public class CustomFileReader { + + private static final String PATH = "src/main/resources/custom_file_reader/input.txt"; + + public CustomFileReader() { + } + + public void run1() { + File file = new File(PATH); + try (Scanner scanner = new Scanner(file)) { + String string = scanner.nextLine(); + String replace = string.replace(".", ""); + System.out.println(replace.replace(",", "")); + } catch (FileNotFoundException ignore) { + } + } + + public void run2() { + Path path = Paths.get(PATH); + try (Stream stream = Files.lines(path)) { + String result = stream + .flatMapToInt(CharSequence::chars) + .filter(c -> c != 44 && c != 46) + .mapToObj(i -> (char) i) + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + System.out.println(result); + } catch (IOException ignore) { + } + } + + public void run3() { + File file = new File(PATH); + try (FileReader fileReader = new FileReader(file)) { + BufferedReader bufferedReader = new BufferedReader(fileReader); + String line = bufferedReader.readLine(); + String replace = line.replace(".", ""); + System.out.println(replace.replace(",", "")); + } catch (IOException e) { + } + + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..e8db6df5 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,10 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + } +} diff --git a/src/main/java/homework_4/singleton/Main.java b/src/main/java/homework_4/singleton/Main.java new file mode 100644 index 00000000..88d979d4 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,12 @@ +package homework_4.singleton; + +public class Main { + + public static void main(String[] args) { + Singleton singleton = Singleton.getInstance(); + Singleton singleton1 = Singleton.getInstance(); + if (singleton == singleton1) { + System.out.println("yes"); + } + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..8e3f38e0 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,17 @@ +package homework_4.singleton; + +public class Singleton { + + private static Singleton singleton = null; + + private Singleton() { + + } + + public static Singleton getInstance() { + if (singleton == null) { + singleton = new Singleton(); + } + return singleton; + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..5c6db802 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,14 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + + private final static String REG_EXP = "^([a-zA-Z0-9])[a-zA-Z0-9._]+@[a-z]+\\.[a-z]*"; + public boolean run() { + Scanner scanner = new Scanner(System.in); + String email = scanner.next(); + return Pattern.matches(REG_EXP, email); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..0de49777 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + System.out.println(new CustomRegexMatcher().run()); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..930f2040 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..3426a6a9 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,32 @@ +package homework_5.power_of_number; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class PowerOfNumber { + private static final String ERROR_MESSAGE = "any problem with input (negative, less/more arguments, string) output: Only 2 non-negative integers are allowed"; + + public void run() { + Scanner scanner = new Scanner(System.in); + String number = scanner.next(); + String power = scanner.next(); + if (number == null || isNotNumber(number) || power == null || isNotNumber(power)) { + System.out.println(ERROR_MESSAGE); + return; + } + int integer = Integer.parseInt(number); + int intPower = Integer.parseInt(power); + System.out.println(recursivePower(integer, intPower)); + } + + private boolean isNotNumber(String str) { + return !Pattern.matches("[0-9]+", str); + } + + public int recursivePower(int number, int power) { + if (power == 0) { + return 1; + } + return number * recursivePower(number, --power); + } +} diff --git a/src/main/resources/custom_file_reader/input.txt b/src/main/resources/custom_file_reader/input.txt new file mode 100644 index 00000000..fd384710 --- /dev/null +++ b/src/main/resources/custom_file_reader/input.txt @@ -0,0 +1 @@ +The text, in a way, consists of a number of sentences. One sentence, even a very widespread, complex one, cannot be called a text, since the text can be divided into independent sentences, and parts of the sentence are combined according to the laws of the syntax of a complex sentence, but not the text. \ No newline at end of file diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java new file mode 100644 index 00000000..8b46be60 --- /dev/null +++ b/src/test/java/base/UnitBase.java @@ -0,0 +1,73 @@ +package base; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public abstract class UnitBase { + + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + +// @Test +// void example() { +// setInput("2"); +// +// new PyramidPrinter().run(); +// printOut(); +// removeFromOutput("Please input number"): +// +// assertEquals("x", getOutputLines()[0]); +// assertEquals("xx", getOutputLines()[1]); +// } + +} diff --git a/src/test/java/homework_1/HomeworkTest.java b/src/test/java/homework_1/HomeworkTest.java new file mode 100644 index 00000000..9299270e --- /dev/null +++ b/src/test/java/homework_1/HomeworkTest.java @@ -0,0 +1,17 @@ +package homework_1; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class HomeworkTest extends UnitBase { + + @Test + public void ErrorArgumentTest() { + String[] strings = new String[]{"word", "another word", "error"}; + String[] stringsExpected = new String[]{"word : 4 letters", "another word : 12 letters", "\u001B[41m" + "Alarm!" + "\u001B[0m"}; + Main.main(strings); + printOut(); + Assertions.assertArrayEquals(stringsExpected, getOutputLines()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..01b42456 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,49 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + + +public class PyramidPrinterTest extends UnitBase { + + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + + @Test + public void notNumberArgumentTest() { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + setInput("number"); + pyramidPrinter.run(); + printOut(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void zeroNumberArgument() { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + setInput("0"); + pyramidPrinter.run(); + printOut(); + Assertions.assertEquals("", getOutputLines()[0]); + } + + @Test + public void negativeNumberArgument() { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + setInput("-1"); + pyramidPrinter.run(); + printOut(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void pyramidTest() { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + setInput("5"); + pyramidPrinter.run(); + printOut(); + String[] expected = "* ** *** **** *****".split(" "); + String[] actual = getOutputLines(); + Assertions.assertArrayEquals(expected, actual); + } +} diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..5fe63395 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,50 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class RandomCharsTableTest extends UnitBase { + + public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + @Test + public void notNumberParamsTest() { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + String input = "number1 number2 even"; + setInput(input); + randomCharsTable.run(); + printOut(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void thirdParamIncorrectTest() { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + String input = "1 2 noEven"; + setInput(input); + randomCharsTable.run(); + printOut(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void correctParams1Test() { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + String input = "1 2 even"; + setInput(input); + randomCharsTable.run(); + printOut(); + Assertions.assertEquals(2, getOutputLines().length); + } + + @Test + public void correctParams2Test() { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + String input = "4 5 even"; + setInput(input); + randomCharsTable.run(); + printOut(); + Assertions.assertEquals(5, getOutputLines().length); + } +} diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..57d6f430 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,58 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class TrafficLightTest extends UnitBase { + + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String DAY_OVER = "The day is over"; + + @Test + public void negativeParamTest() { + TrafficLight trafficLight = new TrafficLight(); + setInput("-1"); + trafficLight.run(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void notNumberParamTest() { + TrafficLight trafficLight = new TrafficLight(); + setInput("number"); + trafficLight.run(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + @Test + public void tooLargeNumberParamTest() { + TrafficLight trafficLight = new TrafficLight(); + setInput("86400"); + trafficLight.run(); + Assertions.assertEquals(DAY_OVER, getOutputLines()[0]); + } + + @ParameterizedTest + @MethodSource("testCases") + public void correctParam1Test(String input, String expected) { + TrafficLight trafficLight = new TrafficLight(); + setInput(input); + trafficLight.run(); + Assertions.assertEquals(expected, getOutputLines()[0]); + } + + public static Stream testCases() { + return Stream.of( + Arguments.of("0", "Green"), + Arguments.of("1", "Green"), + Arguments.of("35", "Yellow"), + Arguments.of("54", "Red") + ); + + } +} \ No newline at end of file diff --git a/src/test/java/homework_3/ImmutableClassTest.java b/src/test/java/homework_3/ImmutableClassTest.java new file mode 100644 index 00000000..0ec43a89 --- /dev/null +++ b/src/test/java/homework_3/ImmutableClassTest.java @@ -0,0 +1,23 @@ +package homework_3; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class ImmutableClassTest { + + @Test + public void immutableClassTest() { + ImmutableClass immutableClass = new ImmutableClass(21, 25, 6, "Vasya"); + ImmutableClass immutableClassAge = immutableClass.changeAge(2); + ImmutableClass immutableClassName = immutableClass.changeName("neVasya"); + ImmutableClass immutableClassHigh = immutableClass.changeWeightAndHigh(2, 22); + + Assertions.assertNotSame(immutableClass, immutableClassAge); + Assertions.assertNotSame(immutableClass, immutableClassHigh); + Assertions.assertNotSame(immutableClass, immutableClassName); + + Assertions.assertNotEquals(immutableClass, immutableClassAge); + Assertions.assertNotEquals(immutableClass, immutableClassName); + Assertions.assertNotEquals(immutableClass, immutableClassHigh); + } +} diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..9ab8af33 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,129 @@ +package homework_4.custom_annotation; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class CustomAnnotationTest { + + @Test + public void defaultValueFieldIntegerTest() { + class TestClass { + @DefaultValue("21") + private Integer integerValue1; + + @DefaultValue("21") + private int integerValue2; + + public Integer getIntegerValue1() { + return integerValue1; + } + + public int getIntegerValue2() { + return integerValue2; + } + } + TestClass testClass = new TestClass(); + try { + DefaulValueImpl.insetDefaultValue(testClass); + Assertions.assertEquals(21, testClass.getIntegerValue1()); + Assertions.assertEquals(21, testClass.getIntegerValue2()); + } catch (Exception ignore) { + } + } + + @Test + public void defaultValueFieldDoubleTest() { + class TestClass { + @DefaultValue("21.2") + private Double doubleValue1; + + @DefaultValue("21.3") + private double doubleValue2; + + public Double getDoubleValue1() { + return doubleValue1; + } + + public double getDoubleValue2() { + return doubleValue2; + } + } + TestClass testClass = new TestClass(); + try { + DefaulValueImpl.insetDefaultValue(testClass); + Assertions.assertEquals(21.2, testClass.getDoubleValue1()); + Assertions.assertEquals(21.3, testClass.getDoubleValue2()); + } catch (Exception ignore) { + } + } + + @Test + public void defaultValueFieldStringTest() { + class TestClass { + @DefaultValue("value1") + private String stringValue1; + + @DefaultValue("anotherValue") + private String stringValue2; + + public String getStringValue1() { + return stringValue1; + } + + public String getStringValue2() { + return stringValue2; + } + } + TestClass testClass = new TestClass(); + try { + DefaulValueImpl.insetDefaultValue(testClass); + Assertions.assertEquals("value1", testClass.getStringValue1()); + Assertions.assertEquals("anotherValue", testClass.getStringValue2()); + } catch (Exception ignore) { + } + } + + @Test + public void defaultValueMethodIntegerParamTest() { + class TestClass { + private Integer integer; + private Double value; + private String str; + + @DefaultValue("11") + public void setInteger(Integer integer) { + this.integer = integer; + } + + @DefaultValue("12.3") + public void setValue(Double value) { + this.value = value; + } + + @DefaultValue("string") + public void setStr(String str) { + this.str = str; + } + + public Integer getInteger() { + return integer; + } + + public Double getDouble() { + return value; + } + + public String getString() { + return str; + } + } + TestClass testClass = new TestClass(); + try { + DefaulValueImpl.insetDefaultValue(testClass); + Assertions.assertEquals(11, testClass.getInteger()); + Assertions.assertEquals(12.3, testClass.getDouble()); + Assertions.assertEquals("string", testClass.getString()); + } catch (Exception ignore) { + } + } +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..1df28649 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,34 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class CustomFileReaderTest extends UnitBase { + + static final String EXPECTED_VALUE = "The text in a way consists of a number of sentences One sentence even a very widespread complex one cannot be called a text since the text can be divided into independent sentences and parts of the sentence are combined according to the laws of the syntax of a complex sentence but not the text"; + + @Test + public void utilReaderTest() { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run1(); + printOut(); + Assertions.assertEquals(EXPECTED_VALUE, getOutputLines()[0]); + } + + @Test + public void nioReaderTest() { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run2(); + printOut(); + Assertions.assertEquals(EXPECTED_VALUE, getOutputLines()[0]); + } + + @Test + public void ioReaderTest() { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run3(); + printOut(); + Assertions.assertEquals(EXPECTED_VALUE, getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..68b4266f --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,14 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class SingletonTest { + + @Test + public void equalsLinkTest() { + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + Assertions.assertSame(singleton1, singleton2); + } +} diff --git a/src/test/java/homework_5/custom_regex_matchers/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matchers/CustomRegexMatcherTest.java new file mode 100644 index 00000000..9547a7bb --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matchers/CustomRegexMatcherTest.java @@ -0,0 +1,51 @@ +package homework_5.custom_regex_matchers; + +import base.UnitBase; +import homework_5.custom_regex_matcher.CustomRegexMatcher; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class CustomRegexMatcherTest extends UnitBase { + + @ParameterizedTest + @MethodSource("testCasesIncorrect") + public void checkIncorrectEmails(String email) { + setInput(email); + CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + Assertions.assertFalse(customRegexMatcher.run()); + } + + public static Stream testCasesIncorrect() { + return Stream.of( + Arguments.of("_awdawd@mail.ru"), + Arguments.of("awdawmail.ru"), + Arguments.of("adwawd@.ru"), + Arguments.of("awdawdw@"), + Arguments.of("awdawdw@mail"), + Arguments.of("awdawdw@ru"), + Arguments.of("awdawdw@."), + Arguments.of("awdawdw@awda_ru") + ); + } + + @ParameterizedTest + @MethodSource("testCasesCorrect") + public void checkCorrectEmails(String email) { + setInput(email); + CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + Assertions.assertTrue(customRegexMatcher.run()); + } + + public static Stream testCasesCorrect() { + return Stream.of( + Arguments.of("awdawd@mail.ru"), + Arguments.of("awdaw@tinkof.com"), + Arguments.of("2.adwawd@group.ru"), + Arguments.of("2_adwawd@group.ru"), + Arguments.of("awda.213wdw@mail.net") + ); + } +} diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..28e2ba50 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,64 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class PowerOfNumberTest extends UnitBase { + + private static final String ERROR_MESSAGE = "any problem with input (negative, less/more arguments, string) output: Only 2 non-negative integers are allowed"; + + @ParameterizedTest + @MethodSource("notNumberCase") + public void paramsNotNumberTest(String firstParam, String secondParam) { + setInput(firstParam + " " + secondParam); + printOut(); + new PowerOfNumber().run(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + public static Stream notNumberCase() { + return Stream.of( + Arguments.of("string", "1"), + Arguments.of("1", "string"), + Arguments.of("string", "string") + ); + } + + @ParameterizedTest + @MethodSource("nullParamsCase") + public void paramsNullTest(String firstParam, String secondParam) { + setInput(firstParam + " " + secondParam); + printOut(); + new PowerOfNumber().run(); + Assertions.assertEquals(ERROR_MESSAGE, getOutputLines()[0]); + } + + public static Stream nullParamsCase() { + return Stream.of( + Arguments.of("1", null), + Arguments.of(null, "string"), + Arguments.of(null, null) + ); + } + + @ParameterizedTest + @MethodSource("correctValueCase") + public void correctValueTest(String firstParam, String secondParam, String expected) { + setInput(firstParam + " " + secondParam); + printOut(); + new PowerOfNumber().run(); + Assertions.assertEquals(expected, getOutputLines()[0]); + } + + public static Stream correctValueCase() { + return Stream.of( + Arguments.of("1", "2", "1"), + Arguments.of("2", "2", "4"), + Arguments.of("5", "5", "3125") + ); + } +}