Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-2221
This commit is contained in:
commit
1dfeb49045
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,93 +1,89 @@
|
|||
package findItems;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindItemsBasedOnValues {
|
||||
|
||||
List<Employee> EmplList = new ArrayList<Employee>();
|
||||
List<Department> deptList = new ArrayList<Department>();
|
||||
|
||||
public static void main(String[] args) throws ParseException {
|
||||
FindItemsBasedOnValues findItems = new FindItemsBasedOnValues();
|
||||
findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
|
||||
Integer expectedId = 1002;
|
||||
|
||||
populate(EmplList, deptList);
|
||||
|
||||
List<Employee> filteredList = EmplList.stream()
|
||||
.filter(empl -> deptList.stream()
|
||||
.anyMatch(dept -> dept.getDepartment()
|
||||
.equals("sales") && empl.getEmployeeId()
|
||||
.equals(dept.getEmployeeId())))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedId, filteredList.get(0)
|
||||
.getEmployeeId());
|
||||
}
|
||||
|
||||
private void populate(List<Employee> EmplList, List<Department> deptList) {
|
||||
Employee employee1 = new Employee(1001, "empl1");
|
||||
Employee employee2 = new Employee(1002, "empl2");
|
||||
Employee employee3 = new Employee(1003, "empl3");
|
||||
|
||||
Collections.addAll(EmplList, employee1, employee2, employee3);
|
||||
|
||||
Department department1 = new Department(1002, "sales");
|
||||
Department department2 = new Department(1003, "marketing");
|
||||
Department department3 = new Department(1004, "sales");
|
||||
|
||||
Collections.addAll(deptList, department1, department2, department3);
|
||||
}
|
||||
}
|
||||
|
||||
class Employee {
|
||||
Integer employeeId;
|
||||
String employeeName;
|
||||
|
||||
public Employee(Integer employeeId, String employeeName) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.employeeName = employeeName;
|
||||
}
|
||||
|
||||
public Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return employeeName;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Department {
|
||||
Integer employeeId;
|
||||
String department;
|
||||
|
||||
public Department(Integer employeeId, String department) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public String getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
package com.baeldung.findItems;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindItemsBasedOnOtherStreamUnitTest {
|
||||
|
||||
private List<Employee> employeeList = new ArrayList<Employee>();
|
||||
|
||||
private List<Department> departmentList = new ArrayList<Department>();
|
||||
|
||||
@Test
|
||||
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
|
||||
Integer expectedId = 1002;
|
||||
|
||||
populate(employeeList, departmentList);
|
||||
|
||||
List<Employee> filteredList = employeeList.stream()
|
||||
.filter(empl -> departmentList.stream()
|
||||
.anyMatch(dept -> dept.getDepartment()
|
||||
.equals("sales") && empl.getEmployeeId()
|
||||
.equals(dept.getEmployeeId())))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedId, filteredList.get(0)
|
||||
.getEmployeeId());
|
||||
}
|
||||
|
||||
private void populate(List<Employee> EmplList, List<Department> deptList) {
|
||||
Employee employee1 = new Employee(1001, "empl1");
|
||||
Employee employee2 = new Employee(1002, "empl2");
|
||||
Employee employee3 = new Employee(1003, "empl3");
|
||||
|
||||
Collections.addAll(EmplList, employee1, employee2, employee3);
|
||||
|
||||
Department department1 = new Department(1002, "sales");
|
||||
Department department2 = new Department(1003, "marketing");
|
||||
Department department3 = new Department(1004, "sales");
|
||||
|
||||
Collections.addAll(deptList, department1, department2, department3);
|
||||
}
|
||||
}
|
||||
|
||||
class Employee {
|
||||
private Integer employeeId;
|
||||
private String employeeName;
|
||||
|
||||
Employee(Integer employeeId, String employeeName) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.employeeName = employeeName;
|
||||
}
|
||||
|
||||
Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return employeeName;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Department {
|
||||
private Integer employeeId;
|
||||
private String department;
|
||||
|
||||
Department(Integer employeeId, String department) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
String getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
}
|
|
@ -184,5 +184,25 @@ public class CompletableFutureLongRunningUnitTest {
|
|||
|
||||
assertEquals("Hello World", future.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException {
|
||||
CompletableFuture<Integer> finalResult = compute().thenApply(s -> s + 1);
|
||||
assertTrue(finalResult.get() == 11);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException {
|
||||
CompletableFuture<Integer> finalResult = compute().thenCompose(this::computeAnother);
|
||||
assertTrue(finalResult.get() == 20);
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> compute(){
|
||||
return CompletableFuture.supplyAsync(() -> 10);
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> computeAnother(Integer i){
|
||||
return CompletableFuture.supplyAsync(() -> 10 + i);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,159 @@
|
|||
package com.baeldung.array;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArrayReferenceGuide {
|
||||
|
||||
public static void main(String[] args) {
|
||||
declaration();
|
||||
|
||||
initialization();
|
||||
|
||||
access();
|
||||
|
||||
iterating();
|
||||
|
||||
varargs();
|
||||
|
||||
transformIntoList();
|
||||
|
||||
transformIntoStream();
|
||||
|
||||
sort();
|
||||
|
||||
search();
|
||||
|
||||
merge();
|
||||
}
|
||||
|
||||
private static void declaration() {
|
||||
int[] anArray;
|
||||
int anotherArray[];
|
||||
}
|
||||
|
||||
private static void initialization() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
}
|
||||
|
||||
private static void access() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
System.out.println(anArray[0]);
|
||||
}
|
||||
|
||||
private static void iterating() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
System.out.println(anArray[i]);
|
||||
}
|
||||
|
||||
for (int element : anArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void varargs() {
|
||||
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
|
||||
varargMethod(groceries);
|
||||
varargMethod("Milk", "Tomato", "Chips");
|
||||
}
|
||||
|
||||
private static void varargMethod(String... varargs) {
|
||||
for (String element : varargs) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void transformIntoList() {
|
||||
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
|
||||
// Naïve implementation
|
||||
List<Integer> aList = new ArrayList<>(); // We create an empty list
|
||||
for (int element : anArray) {
|
||||
// We iterate over array's elements and add them to the list
|
||||
aList.add(element);
|
||||
}
|
||||
|
||||
// Pretty implementation
|
||||
aList = Arrays.asList(anArray);
|
||||
|
||||
// Drawbacks
|
||||
try {
|
||||
aList.remove(0);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
aList.add(6);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
// List<Integer> anotherList = Arrays.asList(anotherArray);
|
||||
}
|
||||
|
||||
private static void transformIntoStream() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
IntStream aStream = Arrays.stream(anArray);
|
||||
|
||||
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
|
||||
}
|
||||
|
||||
private static void sort() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
|
||||
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
|
||||
}
|
||||
|
||||
private static void search() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
if (anArray[i] == 4) {
|
||||
System.out.println("Found at index " + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Arrays.sort(anArray);
|
||||
int index = Arrays.binarySearch(anArray, 4);
|
||||
System.out.println("Found at index " + index);
|
||||
}
|
||||
|
||||
private static void merge() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
|
||||
|
||||
int[] resultArray = new int[anArray.length + anotherArray.length];
|
||||
for (int i = 0; i < resultArray.length; i++) {
|
||||
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
|
||||
}
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
|
||||
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,136 @@
|
|||
package com.baeldung.heapsort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Heap<E extends Comparable<E>> {
|
||||
|
||||
private List<E> elements = new ArrayList<>();
|
||||
|
||||
public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) {
|
||||
Heap<E> heap = of(elements);
|
||||
|
||||
List<E> result = new ArrayList<>();
|
||||
|
||||
while (!heap.isEmpty()) {
|
||||
result.add(heap.pop());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> Heap<E> of(E... elements) {
|
||||
return of(Arrays.asList(elements));
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
|
||||
Heap<E> result = new Heap<>();
|
||||
for (E element : elements) {
|
||||
result.add(element);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void add(E e) {
|
||||
elements.add(e);
|
||||
int elementIndex = elements.size() - 1;
|
||||
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
|
||||
int parentIndex = parentIndex(elementIndex);
|
||||
swap(elementIndex, parentIndex);
|
||||
elementIndex = parentIndex;
|
||||
}
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (isEmpty()) {
|
||||
throw new IllegalStateException("You cannot pop from an empty heap");
|
||||
}
|
||||
|
||||
E result = elementAt(0);
|
||||
|
||||
int lasElementIndex = elements.size() - 1;
|
||||
swap(0, lasElementIndex);
|
||||
elements.remove(lasElementIndex);
|
||||
|
||||
int elementIndex = 0;
|
||||
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
|
||||
int smallerChildIndex = smallerChildIndex(elementIndex);
|
||||
swap(elementIndex, smallerChildIndex);
|
||||
elementIndex = smallerChildIndex;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return elements.isEmpty();
|
||||
}
|
||||
|
||||
private boolean isRoot(int index) {
|
||||
return index == 0;
|
||||
}
|
||||
|
||||
private int smallerChildIndex(int index) {
|
||||
int leftChildIndex = leftChildIndex(index);
|
||||
int rightChildIndex = rightChildIndex(index);
|
||||
|
||||
if (!isValidIndex(rightChildIndex)) {
|
||||
return leftChildIndex;
|
||||
}
|
||||
|
||||
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
|
||||
return leftChildIndex;
|
||||
}
|
||||
|
||||
return rightChildIndex;
|
||||
}
|
||||
|
||||
private boolean isLeaf(int index) {
|
||||
return !isValidIndex(leftChildIndex(index));
|
||||
}
|
||||
|
||||
private boolean isCorrectParent(int index) {
|
||||
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
|
||||
}
|
||||
|
||||
private boolean isCorrectChild(int index) {
|
||||
return isCorrect(parentIndex(index), index);
|
||||
}
|
||||
|
||||
private boolean isCorrect(int parentIndex, int childIndex) {
|
||||
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
|
||||
}
|
||||
|
||||
private boolean isValidIndex(int index) {
|
||||
return index < elements.size();
|
||||
}
|
||||
|
||||
private void swap(int index1, int index2) {
|
||||
E element1 = elementAt(index1);
|
||||
E element2 = elementAt(index2);
|
||||
elements.set(index1, element2);
|
||||
elements.set(index2, element1);
|
||||
}
|
||||
|
||||
private E elementAt(int index) {
|
||||
return elements.get(index);
|
||||
}
|
||||
|
||||
private int parentIndex(int index) {
|
||||
return (index - 1) / 2;
|
||||
}
|
||||
|
||||
private int leftChildIndex(int index) {
|
||||
return 2 * index + 1;
|
||||
}
|
||||
|
||||
private int rightChildIndex(int index) {
|
||||
return 2 * index + 2;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.heapsort;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HeapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
|
||||
// given
|
||||
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
|
||||
|
||||
// when
|
||||
int head = heap.pop();
|
||||
|
||||
// then
|
||||
assertThat(head).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
|
||||
// given
|
||||
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);
|
||||
|
||||
// when
|
||||
List<Integer> sortedElements = Heap.sort(elements);
|
||||
|
||||
// then
|
||||
assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.modulo;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Java6Assertions.*;
|
||||
|
||||
public class ModuloUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenIntegerDivision_thenLosesRemainder(){
|
||||
assertThat(11 / 4).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDoubleDivision_thenKeepsRemainder(){
|
||||
assertThat(11 / 4.0).isEqualTo(2.75);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModulo_thenReturnsRemainder(){
|
||||
assertThat(11 % 4).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDivisionByZero_thenArithmeticException(){
|
||||
double result = 1 / 0;
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenModuloByZero_thenArithmeticException(){
|
||||
double result = 1 % 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
|
||||
assertThat(3 % 2).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
|
||||
assertThat(4 % 2).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
|
||||
int QUEUE_CAPACITY= 10;
|
||||
int[] circularQueue = new int[QUEUE_CAPACITY];
|
||||
int itemsInserted = 0;
|
||||
for (int value = 0; value < 1000; value++) {
|
||||
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
|
||||
circularQueue[writeIndex] = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.interfaces
|
||||
|
||||
interface BaseInterface {
|
||||
fun someMethod(): String
|
||||
}
|
||||
|
||||
interface FirstChildInterface : BaseInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in FirstChildInterface")
|
||||
}
|
||||
}
|
||||
|
||||
interface SecondChildInterface : BaseInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in SecondChildInterface")
|
||||
}
|
||||
}
|
||||
|
||||
class ChildClass : FirstChildInterface, SecondChildInterface {
|
||||
override fun someMethod(): String {
|
||||
return super<SecondChildInterface>.someMethod()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.interfaces
|
||||
|
||||
interface MyInterface {
|
||||
fun someMethod(): String
|
||||
}
|
||||
|
||||
class MyClass() : MyInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, World!")
|
||||
}
|
||||
}
|
||||
|
||||
class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.interfaces
|
||||
|
||||
interface FirstInterface {
|
||||
fun someMethod(): String
|
||||
|
||||
fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in FirstInterface")
|
||||
}
|
||||
}
|
||||
|
||||
interface SecondInterface {
|
||||
fun someMethod(): String {
|
||||
return("Hello, from someMethod in SecondInterface")
|
||||
}
|
||||
|
||||
fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in SecondInterface")
|
||||
}
|
||||
}
|
||||
|
||||
class SomeClass: FirstInterface, SecondInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in SomeClass")
|
||||
}
|
||||
|
||||
override fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in SomeClass")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.interfaces
|
||||
|
||||
interface SimpleInterface {
|
||||
val firstProp: String
|
||||
val secondProp: String
|
||||
get() = "Second Property"
|
||||
fun firstMethod(): String
|
||||
fun secondMethod(): String {
|
||||
println("Hello, from: " + secondProp)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleClass: SimpleInterface {
|
||||
override val firstProp: String = "First Property"
|
||||
override val secondProp: String
|
||||
get() = "Second Property, Overridden!"
|
||||
override fun firstMethod(): String {
|
||||
return("Hello, from: " + firstProp)
|
||||
}
|
||||
override fun secondMethod(): String {
|
||||
return("Hello, from: " + secondProp + firstProp)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.interfaces
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class InterfaceExamplesUnitTest {
|
||||
@Test
|
||||
fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() {
|
||||
val simpleClass = SimpleClass()
|
||||
assertEquals("Hello, from: First Property", simpleClass.firstMethod())
|
||||
assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||
val someClass = SomeClass()
|
||||
assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod())
|
||||
assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||
val childClass = ChildClass()
|
||||
assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() {
|
||||
val myClass = MyClass()
|
||||
assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1,20 @@
|
|||
=========
|
||||
|
||||
## Guava and Hamcrest Cookbooks and Examples
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
||||
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
||||
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
||||
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
||||
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
|
@ -0,0 +1,66 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-collections</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>24.0-jre</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -0,0 +1 @@
|
|||
John Jane Adam Tom
|
|
@ -0,0 +1 @@
|
|||
Hello world
|
|
@ -0,0 +1 @@
|
|||
Test
|
|
@ -0,0 +1,4 @@
|
|||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
|
@ -0,0 +1 @@
|
|||
Hello world
|
Binary file not shown.
|
@ -4,33 +4,19 @@
|
|||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
||||
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
||||
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
|
||||
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
||||
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
||||
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||
- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file)
|
||||
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering)
|
||||
- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions)
|
||||
- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader)
|
||||
- [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer)
|
||||
- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus)
|
||||
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
||||
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||
- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
|
||||
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
|
||||
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
|
||||
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
|
||||
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
|
|
|
@ -14,12 +14,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
|
@ -56,7 +50,6 @@
|
|||
<!-- util -->
|
||||
<guava.version>24.0-jre</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
|
|
|
@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
|
||||
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
|
||||
- [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints)
|
||||
- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
|
||||
|
|
|
@ -358,6 +358,7 @@
|
|||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<type>pom</type>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -922,7 +923,7 @@
|
|||
<quartz.version>2.3.0</quartz.version>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
<jmh.version>1.19</jmh.version>
|
||||
<groovy.version>2.4.10</groovy.version>
|
||||
<groovy.version>2.5.2</groovy.version>
|
||||
<noexception.version>1.1.0</noexception.version>
|
||||
<logging-interceptor.version>3.9.0</logging-interceptor.version>
|
||||
<yarg.version>2.0.4</yarg.version>
|
||||
|
|
|
@ -6,8 +6,10 @@ import org.apache.commons.lang3.SystemUtils;
|
|||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SystemsUtilsUnitTest {
|
||||
public class SystemsUtilsManualTest {
|
||||
|
||||
// the paths depend on the OS and installed version of Java
|
||||
|
||||
@Test
|
||||
public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() {
|
||||
assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre"));
|
0
logging-modules/log4j2/${sys:logging.folder.path} → logging-modules/log4j2/${sys
Executable file → Normal file
0
logging-modules/log4j2/${sys:logging.folder.path} → logging-modules/log4j2/${sys
Executable file → Normal file
|
@ -17,7 +17,7 @@
|
|||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>1.5.15.RELEASE</version>
|
||||
<version>1.5.16.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
|
8
pom.xml
8
pom.xml
|
@ -46,6 +46,12 @@
|
|||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
|
@ -373,6 +379,7 @@
|
|||
<module>google-web-toolkit</module>
|
||||
<module>gson</module>
|
||||
<module>guava</module>
|
||||
<module>guava-collections</module>
|
||||
<module>guava-modules/guava-18</module>
|
||||
<module>guava-modules/guava-19</module>
|
||||
<module>guava-modules/guava-21</module>
|
||||
|
@ -1280,6 +1287,7 @@
|
|||
<module>google-cloud</module>
|
||||
<module>gson</module>
|
||||
<module>guava</module>
|
||||
<module>guava-collections</module>
|
||||
<module>guava-modules/guava-18</module>
|
||||
<module>guava-modules/guava-19</module>
|
||||
<module>guava-modules/guava-21</module>
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.validations.functional;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class FunctionalValidationsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(FunctionalValidationsApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.validations.functional.handlers;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.BeanPropertyBindingResult;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public abstract class AbstractValidationHandler<T, U extends Validator> {
|
||||
|
||||
private final Class<T> validationClass;
|
||||
|
||||
private final U validator;
|
||||
|
||||
protected AbstractValidationHandler(Class<T> clazz, U validator) {
|
||||
this.validationClass = clazz;
|
||||
this.validator = validator;
|
||||
}
|
||||
|
||||
abstract protected Mono<ServerResponse> processBody(T validBody, final ServerRequest originalRequest);
|
||||
|
||||
public final Mono<ServerResponse> handleRequest(final ServerRequest request) {
|
||||
return request.bodyToMono(this.validationClass)
|
||||
.flatMap(body -> {
|
||||
Errors errors = new BeanPropertyBindingResult(body, this.validationClass.getName());
|
||||
this.validator.validate(body, errors);
|
||||
|
||||
if (errors == null || errors.getAllErrors()
|
||||
.isEmpty()) {
|
||||
return processBody(body, request);
|
||||
} else {
|
||||
return onValidationErrors(errors, body, request);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected Mono<ServerResponse> onValidationErrors(Errors errors, T invalidBody, final ServerRequest request) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors()
|
||||
.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.validations.functional.handlers;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.BeanPropertyBindingResult;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import com.baeldung.validations.functional.model.CustomRequestEntity;
|
||||
import com.baeldung.validations.functional.validators.CustomRequestEntityValidator;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class FunctionalHandler {
|
||||
|
||||
public Mono<ServerResponse> handleRequest(final ServerRequest request) {
|
||||
Validator validator = new CustomRequestEntityValidator();
|
||||
Mono<String> responseBody = request.bodyToMono(CustomRequestEntity.class)
|
||||
.map(body -> {
|
||||
Errors errors = new BeanPropertyBindingResult(body, CustomRequestEntity.class.getName());
|
||||
validator.validate(body, errors);
|
||||
|
||||
if (errors == null || errors.getAllErrors()
|
||||
.isEmpty()) {
|
||||
return String.format("Hi, %s [%s]!", body.getName(), body.getCode());
|
||||
|
||||
} else {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors()
|
||||
.toString());
|
||||
}
|
||||
|
||||
});
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(responseBody, String.class);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.validations.functional.handlers.impl;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import com.baeldung.validations.functional.handlers.AbstractValidationHandler;
|
||||
import com.baeldung.validations.functional.model.AnnotatedRequestEntity;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class AnnotatedRequestEntityValidationHandler extends AbstractValidationHandler<AnnotatedRequestEntity, Validator> {
|
||||
|
||||
private AnnotatedRequestEntityValidationHandler(@Autowired Validator validator) {
|
||||
super(AnnotatedRequestEntity.class, validator);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Mono<ServerResponse> processBody(AnnotatedRequestEntity validBody, ServerRequest originalRequest) {
|
||||
String responseBody = String.format("Hi, %s. Password: %s!", validBody.getUser(), validBody.getPassword());
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Mono.just(responseBody), String.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.validations.functional.handlers.impl;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import com.baeldung.validations.functional.handlers.AbstractValidationHandler;
|
||||
import com.baeldung.validations.functional.model.CustomRequestEntity;
|
||||
import com.baeldung.validations.functional.validators.CustomRequestEntityValidator;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class CustomRequestEntityValidationHandler extends AbstractValidationHandler<CustomRequestEntity, CustomRequestEntityValidator> {
|
||||
|
||||
private CustomRequestEntityValidationHandler() {
|
||||
super(CustomRequestEntity.class, new CustomRequestEntityValidator());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Mono<ServerResponse> processBody(CustomRequestEntity validBody, ServerRequest originalRequest) {
|
||||
String responseBody = String.format("Hi, %s [%s]!", validBody.getName(), validBody.getCode());
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Mono.just(responseBody), String.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Mono<ServerResponse> onValidationErrors(Errors errors, CustomRequestEntity invalidBody, final ServerRequest request) {
|
||||
return ServerResponse.badRequest()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Mono.just(String.format("Custom message showing the errors: %s", errors.getAllErrors()
|
||||
.toString())), String.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.validations.functional.handlers.impl;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import com.baeldung.validations.functional.handlers.AbstractValidationHandler;
|
||||
import com.baeldung.validations.functional.model.OtherEntity;
|
||||
import com.baeldung.validations.functional.validators.OtherEntityValidator;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class OtherEntityValidationHandler extends AbstractValidationHandler<OtherEntity, OtherEntityValidator> {
|
||||
|
||||
private OtherEntityValidationHandler() {
|
||||
super(OtherEntity.class, new OtherEntityValidator());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Mono<ServerResponse> processBody(OtherEntity validBody, ServerRequest originalRequest) {
|
||||
String responseBody = String.format("Other object with item %s and quantity %s!", validBody.getItem(), validBody.getQuantity());
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(Mono.just(responseBody), String.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.validations.functional.model;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class AnnotatedRequestEntity {
|
||||
@NotNull
|
||||
private String user;
|
||||
|
||||
@NotNull
|
||||
@Size(min = 4, max = 7)
|
||||
private String password;
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.validations.functional.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class CustomRequestEntity {
|
||||
|
||||
private String name;
|
||||
private String code;
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.validations.functional.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class OtherEntity {
|
||||
|
||||
private String item;
|
||||
private Integer quantity;
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.validations.functional.routers;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.server.RequestPredicates;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import com.baeldung.validations.functional.handlers.FunctionalHandler;
|
||||
import com.baeldung.validations.functional.handlers.impl.AnnotatedRequestEntityValidationHandler;
|
||||
import com.baeldung.validations.functional.handlers.impl.CustomRequestEntityValidationHandler;
|
||||
import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHandler;
|
||||
|
||||
@Configuration
|
||||
public class ValidationsRouters {
|
||||
|
||||
@Bean
|
||||
public RouterFunction<ServerResponse> responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler,
|
||||
@Autowired FunctionalHandler complexHandler,
|
||||
@Autowired OtherEntityValidationHandler otherHandler,
|
||||
@Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) {
|
||||
return RouterFunctions.route(RequestPredicates.POST("/complex-handler-functional-validation"), complexHandler::handleRequest)
|
||||
.andRoute(RequestPredicates.POST("/dry-functional-validation"), dryHandler::handleRequest)
|
||||
.andRoute(RequestPredicates.POST("/other-dry-functional-validation"), otherHandler::handleRequest)
|
||||
.andRoute(RequestPredicates.POST("/annotated-functional-validation"), annotatedEntityHandler::handleRequest);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.validations.functional.validators;
|
||||
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.ValidationUtils;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
import com.baeldung.validations.functional.model.CustomRequestEntity;
|
||||
|
||||
public class CustomRequestEntityValidator implements Validator {
|
||||
|
||||
private static final int MINIMUM_CODE_LENGTH = 6;
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return CustomRequestEntity.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "field.required");
|
||||
CustomRequestEntity request = (CustomRequestEntity) target;
|
||||
if (request.getCode() != null && request.getCode()
|
||||
.trim()
|
||||
.length() < MINIMUM_CODE_LENGTH) {
|
||||
errors.rejectValue("code", "field.min.length", new Object[] { Integer.valueOf(MINIMUM_CODE_LENGTH) }, "The code must be at least [" + MINIMUM_CODE_LENGTH + "] characters in length.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.validations.functional.validators;
|
||||
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.ValidationUtils;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
import com.baeldung.validations.functional.model.OtherEntity;
|
||||
|
||||
public class OtherEntityValidator implements Validator {
|
||||
|
||||
private static final int MIN_ITEM_QUANTITY = 1;
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return OtherEntity.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "item", "field.required");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "quantity", "field.required");
|
||||
OtherEntity request = (OtherEntity) target;
|
||||
if (request.getQuantity() != null && request.getQuantity() < MIN_ITEM_QUANTITY) {
|
||||
errors.rejectValue("quantity", "field.min.length", new Object[] { Integer.valueOf(MIN_ITEM_QUANTITY) }, "There must be at least one item");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.validations.functional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
|
||||
|
||||
import com.baeldung.validations.functional.model.AnnotatedRequestEntity;
|
||||
import com.baeldung.validations.functional.model.CustomRequestEntity;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class FunctionalEndpointValidationsLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080";
|
||||
private static final String COMPLEX_EP_URL = BASE_URL + "/complex-handler-functional-validation";
|
||||
private static final String DRY_EP_URL = BASE_URL + "/dry-functional-validation";
|
||||
private static final String ANNOTATIONS_EP_URL = BASE_URL + "/annotated-functional-validation";
|
||||
|
||||
private static WebTestClient client;
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl(BASE_URL)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingDryEPWithInvalidBody_thenObtainBadRequest() {
|
||||
CustomRequestEntity body = new CustomRequestEntity("name", "123");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(DRY_EP_URL)
|
||||
.body(Mono.just(body), CustomRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingComplexEPWithInvalidBody_thenObtainBadRequest() {
|
||||
CustomRequestEntity body = new CustomRequestEntity("name", "123");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(COMPLEX_EP_URL)
|
||||
.body(Mono.just(body), CustomRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingAnnotatedEPWithInvalidBody_thenObtainBadRequest() {
|
||||
AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "passwordlongerthan7digits");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(ANNOTATIONS_EP_URL)
|
||||
.body(Mono.just(body), AnnotatedRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingDryEPWithValidBody_thenObtainBadRequest() {
|
||||
CustomRequestEntity body = new CustomRequestEntity("name", "1234567");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(DRY_EP_URL)
|
||||
.body(Mono.just(body), CustomRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isOk();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingComplexEPWithValidBody_thenObtainBadRequest() {
|
||||
CustomRequestEntity body = new CustomRequestEntity("name", "1234567");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(COMPLEX_EP_URL)
|
||||
.body(Mono.just(body), CustomRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isOk();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingAnnotatedEPWithValidBody_thenObtainBadRequest() {
|
||||
AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "12345");
|
||||
|
||||
ResponseSpec response = client.post()
|
||||
.uri(ANNOTATIONS_EP_URL)
|
||||
.body(Mono.just(body), AnnotatedRequestEntity.class)
|
||||
.exchange();
|
||||
|
||||
response.expectStatus()
|
||||
.isOk();
|
||||
}
|
||||
}
|
|
@ -4,7 +4,7 @@ import org.springframework.boot.SpringApplication;
|
|||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.h2db.auto-configuration")
|
||||
@SpringBootApplication
|
||||
public class AutoConfigurationDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.junit5vstestng;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SummationServiceIntegrationTest {
|
||||
private static List<Integer> numbers;
|
||||
|
||||
@BeforeAll
|
||||
public static void initialize() {
|
||||
numbers = new ArrayList<>();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void tearDown() {
|
||||
numbers = null;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void runBeforeEachTest() {
|
||||
numbers.add(1);
|
||||
numbers.add(2);
|
||||
numbers.add(3);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void runAfterEachTest() {
|
||||
numbers.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumbers_sumEquals_thenCorrect() {
|
||||
int sum = numbers.stream()
|
||||
.reduce(0, Integer::sum);
|
||||
Assert.assertEquals(6, sum);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void givenEmptyList_sumEqualsZero_thenCorrect() {
|
||||
int sum = numbers.stream()
|
||||
.reduce(0, Integer::sum);
|
||||
Assert.assertEquals(6, sum);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package org.baeldung.java.customtestname;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
public class CustomNameUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = { "Hello", "World" })
|
||||
@DisplayName("Test Method to check that the inputs are not nullable")
|
||||
void givenString_TestNullOrNot(String word) {
|
||||
assertNotNull(word);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package org.baeldung.java.parameterisedsource;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
public class ParameterizedUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = { "Hello", "World" })
|
||||
void givenString_TestNullOrNot(String word) {
|
||||
assertNotNull(word);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"})
|
||||
void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) {
|
||||
assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("wordDataProvider")
|
||||
void givenMethodSource_TestInputStream(String argument) {
|
||||
assertNotNull(argument);
|
||||
}
|
||||
|
||||
static Stream<String> wordDataProvider() {
|
||||
return Stream.of("foo", "bar");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({ "1, Car", "2, House", "3, Train" })
|
||||
void givenCSVSource_TestContent(int id, String word) {
|
||||
assertNotNull(id);
|
||||
assertNotNull(word);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package org.baeldung.java.parameterisedsource;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS,
|
||||
NORMAL;
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.java.suite;
|
||||
|
||||
import org.baeldung.java.suite.childpackage1.Class1UnitTest;
|
||||
import org.baeldung.java.suite.childpackage2.Class2UnitTest;
|
||||
import org.junit.platform.runner.JUnitPlatform;
|
||||
import org.junit.platform.suite.api.SelectClasses;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(JUnitPlatform.class)
|
||||
@SelectClasses({Class1UnitTest.class, Class2UnitTest.class})
|
||||
public class SelectClassesSuiteUnitTest {
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package org.baeldung.java.suite;
|
||||
|
||||
import org.junit.platform.runner.JUnitPlatform;
|
||||
import org.junit.platform.suite.api.SelectPackages;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(JUnitPlatform.class)
|
||||
@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" })
|
||||
public class SelectPackagesSuiteUnitTest {
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package org.baeldung.java.suite.childpackage1;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class Class1UnitTest {
|
||||
|
||||
@Test
|
||||
public void testCase_InClass1UnitTest() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.java.suite.childpackage2;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Class2UnitTest {
|
||||
|
||||
@Test
|
||||
public void testCase_InClass2UnitTest() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue