Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
2dbb9e0dad
|
@ -4,7 +4,7 @@ before_install:
|
|||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
|
||||
|
||||
sudo: required
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.heapsort;
|
||||
package com.baeldung.algorithms.heapsort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.heapsort;
|
||||
package com.baeldung.algorithms.heapsort;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
|
@ -32,3 +32,4 @@
|
|||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -55,3 +55,4 @@
|
|||
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
|
||||
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
public class CollectionRemoveIf {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
names.removeIf(e -> e.startsWith("A"));
|
||||
System.out.println(String.join(",", names));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Iterators {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Iterator<String> i = names.iterator();
|
||||
|
||||
while (i.hasNext()) {
|
||||
String e = i.next();
|
||||
if (e.startsWith("A")) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(String.join(",", names));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamFilterAndCollector {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Collection<String> filteredCollection = names
|
||||
.stream()
|
||||
.filter(e -> !e.startsWith("A"))
|
||||
.collect(Collectors.toList());
|
||||
System.out.println(String.join(",", filteredCollection));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamPartitioningBy {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Map<Boolean, List<String>> classifiedElements = names
|
||||
.stream()
|
||||
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
|
||||
|
||||
String matching = String.join(",", classifiedElements.get(Boolean.TRUE));
|
||||
String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE));
|
||||
System.out.println("Matching elements: " + matching);
|
||||
System.out.println("Non matching elements: " + nonMatching);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.removal;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class RemovalUnitTest {
|
||||
|
||||
Collection<String> names;
|
||||
Collection<String> expected;
|
||||
Collection<String> removed;
|
||||
|
||||
@Before
|
||||
public void setupTestData() {
|
||||
names = new ArrayList<>();
|
||||
expected = new ArrayList<>();
|
||||
removed = new ArrayList<>();
|
||||
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
expected.add("John");
|
||||
expected.add("Mary");
|
||||
expected.add("Mark");
|
||||
|
||||
removed.add("Ana");
|
||||
removed.add("Anthony");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
Iterator<String> i = names.iterator();
|
||||
|
||||
while (i.hasNext()) {
|
||||
String e = i.next();
|
||||
if (e.startsWith("A")) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(names, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
names.removeIf(e -> e.startsWith("A"));
|
||||
assertThat(names, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
Collection<String> filteredCollection = names
|
||||
.stream()
|
||||
.filter(e -> !e.startsWith("A"))
|
||||
.collect(Collectors.toList());
|
||||
assertThat(filteredCollection, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() {
|
||||
Map<Boolean, List<String>> classifiedElements = names
|
||||
.stream()
|
||||
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
|
||||
|
||||
assertThat(classifiedElements.get(Boolean.TRUE), is(expected));
|
||||
assertThat(classifiedElements.get(Boolean.FALSE), is(removed));
|
||||
}
|
||||
|
||||
}
|
|
@ -29,7 +29,6 @@
|
|||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
|
||||
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
|
||||
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
|
@ -150,9 +149,11 @@
|
|||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
|
||||
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
|
||||
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
|
||||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
|
||||
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
|
||||
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
|
||||
|
|
|
@ -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,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,23 @@
|
|||
=========
|
||||
|
||||
## 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)
|
||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
|
@ -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,16 @@
|
|||
|
||||
|
||||
### 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>
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.jackson.xmlToJson;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
|
@ -14,43 +12,32 @@ import java.io.IOException;
|
|||
public class XmlToJsonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() {
|
||||
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{
|
||||
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
|
||||
|
||||
try {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
|
||||
|
||||
assertEquals(poppy.getName(), "Poppy");
|
||||
assertEquals(poppy.getColor(), Color.RED);
|
||||
assertEquals(poppy.getPetals(), new Integer(9));
|
||||
assertEquals(poppy.getName(), "Poppy");
|
||||
assertEquals(poppy.getColor(), Color.RED);
|
||||
assertEquals(poppy.getPetals(), new Integer(9));
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String json = mapper.writeValueAsString(poppy);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String json = mapper.writeValueAsString(poppy);
|
||||
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
|
||||
System.out.println(json);
|
||||
} catch(IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() {
|
||||
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException {
|
||||
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
|
||||
|
||||
try {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
|
||||
|
||||
ObjectMapper jsonMapper = new ObjectMapper();
|
||||
String json = jsonMapper.writeValueAsString(node);
|
||||
ObjectMapper jsonMapper = new ObjectMapper();
|
||||
String json = jsonMapper.writeValueAsString(node);
|
||||
|
||||
System.out.println(json);
|
||||
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
|
||||
} catch(IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.maths;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
@ -11,10 +12,10 @@ public class MathSinUnitTest {
|
|||
double angleInDegrees = 30;
|
||||
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
|
||||
|
||||
double thirtyDegreesInRadians = 1/6 * Math.PI;
|
||||
double thirtyDegreesInRadians = (double) 1 / 6 * Math.PI;
|
||||
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
|
||||
|
||||
assertTrue(sinForDegrees == sinForRadians);
|
||||
assertThat(sinForDegrees, is(sinForRadians));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -27,6 +27,7 @@
|
|||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
|
||||
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
|
||||
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
|
||||
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
|
||||
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
|
||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||
|
|
|
@ -68,7 +68,17 @@
|
|||
<artifactId>emoji-java</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Added for password generation -->
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>1.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,152 @@
|
|||
package com.baeldung.string.password;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.text.RandomStringGenerator;
|
||||
import org.passay.CharacterData;
|
||||
import org.passay.CharacterRule;
|
||||
import org.passay.EnglishCharacterData;
|
||||
import org.passay.PasswordGenerator;
|
||||
|
||||
public class RandomPasswordGenerator {
|
||||
|
||||
/**
|
||||
* Special characters allowed in password.
|
||||
*/
|
||||
public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+";
|
||||
|
||||
public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS";
|
||||
|
||||
Random random = new SecureRandom();
|
||||
|
||||
public String generatePassayPassword() {
|
||||
PasswordGenerator gen = new PasswordGenerator();
|
||||
CharacterData lowerCaseChars = EnglishCharacterData.LowerCase;
|
||||
CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars);
|
||||
lowerCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData upperCaseChars = EnglishCharacterData.UpperCase;
|
||||
CharacterRule upperCaseRule = new CharacterRule(upperCaseChars);
|
||||
upperCaseRule.setNumberOfCharacters(2);
|
||||
CharacterData digitChars = EnglishCharacterData.Digit;
|
||||
CharacterRule digitRule = new CharacterRule(digitChars);
|
||||
digitRule.setNumberOfCharacters(2);
|
||||
CharacterData specialChars = new CharacterData() {
|
||||
public String getErrorCode() {
|
||||
return ERROR_CODE;
|
||||
}
|
||||
|
||||
public String getCharacters() {
|
||||
return ALLOWED_SPL_CHARACTERS;
|
||||
}
|
||||
};
|
||||
CharacterRule splCharRule = new CharacterRule(specialChars);
|
||||
splCharRule.setNumberOfCharacters(2);
|
||||
String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule);
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonTextPassword() {
|
||||
String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2))
|
||||
.concat(generateRandomAlphabet(2, true))
|
||||
.concat(generateRandomAlphabet(2, false))
|
||||
.concat(generateRandomCharacters(2));
|
||||
List<Character> pwChars = pwString.chars()
|
||||
.mapToObj(data -> (char) data)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwChars);
|
||||
String password = pwChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateCommonsLang3Password() {
|
||||
String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true);
|
||||
String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true);
|
||||
String numbers = RandomStringUtils.randomNumeric(2);
|
||||
String specialChar = RandomStringUtils.random(2, 33, 47, false, false);
|
||||
String totalChars = RandomStringUtils.randomAlphanumeric(2);
|
||||
String combinedChars = upperCaseLetters.concat(lowerCaseLetters)
|
||||
.concat(numbers)
|
||||
.concat(specialChar)
|
||||
.concat(totalChars);
|
||||
List<Character> pwdChars = combinedChars.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toList());
|
||||
Collections.shuffle(pwdChars);
|
||||
String password = pwdChars.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateSecureRandomPassword() {
|
||||
Stream<Character> pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false))));
|
||||
List<Character> charList = pwdStream.collect(Collectors.toList());
|
||||
Collections.shuffle(charList);
|
||||
String password = charList.stream()
|
||||
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
||||
.toString();
|
||||
return password;
|
||||
}
|
||||
|
||||
public String generateRandomSpecialCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomNumbers(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomCharacters(int length) {
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public String generateRandomAlphabet(int length, boolean lowerCase) {
|
||||
int low;
|
||||
int hi;
|
||||
if (lowerCase) {
|
||||
low = 97;
|
||||
hi = 122;
|
||||
} else {
|
||||
low = 65;
|
||||
hi = 90;
|
||||
}
|
||||
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
|
||||
.build();
|
||||
return pwdGenerator.generate(length);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
|
||||
IntStream characters = null;
|
||||
if (upperCase) {
|
||||
characters = random.ints(count, 65, 90);
|
||||
} else {
|
||||
characters = random.ints(count, 97, 122);
|
||||
}
|
||||
return characters.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomNumbers(int count) {
|
||||
IntStream numbers = random.ints(count, 48, 57);
|
||||
return numbers.mapToObj(data -> (char) data);
|
||||
}
|
||||
|
||||
public Stream<Character> getRandomSpecialChars(int count) {
|
||||
IntStream specialChars = random.ints(count, 33, 45);
|
||||
return specialChars.mapToObj(data -> (char) data);
|
||||
}
|
||||
}
|
|
@ -56,5 +56,4 @@ public class StringToByteArrayUnitTest {
|
|||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.string.password;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Examples of passwords conforming to various specifications, using different libraries.
|
||||
*
|
||||
*/
|
||||
public class StringPasswordUnitTest {
|
||||
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingPassay_thenSuccessful() {
|
||||
String password = passGen.generatePassayPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Passay", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() {
|
||||
RandomPasswordGenerator passGen = new RandomPasswordGenerator();
|
||||
String password = passGen.generateCommonTextPassword();
|
||||
int lowerCaseCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 97 || c <= 122) {
|
||||
lowerCaseCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-text ", lowerCaseCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() {
|
||||
String password = passGen.generateCommonsLang3Password();
|
||||
int numCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 48 || c <= 57) {
|
||||
numCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in commons-lang3", numCount >= 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() {
|
||||
String password = passGen.generateSecureRandomPassword();
|
||||
int specialCharCount = 0;
|
||||
for (char c : password.toCharArray()) {
|
||||
if (c >= 33 || c <= 47) {
|
||||
specialCharCount++;
|
||||
}
|
||||
}
|
||||
assertTrue("Password validation failed in Secure Random", specialCharCount >= 2);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
<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>
|
||||
<artifactId>jib</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jib</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>0.9.10</version>
|
||||
<configuration>
|
||||
<to>
|
||||
<image>registry.hub.docker.com/baeldungjib/jib-spring-boot-app</image>
|
||||
</to>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-releases</id>
|
||||
<url>https://repo.spring.io/libs-release</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-releases</id>
|
||||
<url>https://repo.spring.io/libs-release</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung;
|
||||
|
||||
public class Greeting {
|
||||
|
||||
private final long id;
|
||||
private final String content;
|
||||
|
||||
public Greeting(long id, String content) {
|
||||
this.id = id;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@RestController
|
||||
public class GreetingController {
|
||||
|
||||
private static final String template = "Hello Docker, %s!";
|
||||
private final AtomicLong counter = new AtomicLong();
|
||||
|
||||
@GetMapping("/greeting")
|
||||
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
|
||||
return new Greeting(counter.incrementAndGet(),
|
||||
String.format(template, name));
|
||||
}
|
||||
}
|
|
@ -711,6 +711,12 @@
|
|||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.numericalmethod</groupId>
|
||||
<artifactId>suanshu</artifactId>
|
||||
<version>${suanshu.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
@ -731,6 +737,12 @@
|
|||
<id>Apache Staging</id>
|
||||
<url>https://repository.apache.org/content/groups/staging</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>nm-repo</id>
|
||||
<name>Numerical Method's Maven Repository</name>
|
||||
<url>http://repo.numericalmethod.com/maven/</url>
|
||||
<layout>default</layout>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
|
||||
|
@ -835,6 +847,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<suanshu.version>4.0.0</suanshu.version>
|
||||
<snakeyaml.version>1.21</snakeyaml.version>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
<crdt.version>0.1.0</crdt.version>
|
||||
|
|
|
@ -0,0 +1,142 @@
|
|||
package com.baeldung.suanshu;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.Matrix;
|
||||
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.Vector;
|
||||
import com.numericalmethod.suanshu.algebra.linear.vector.doubles.dense.DenseVector;
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.matrixtype.dense.DenseMatrix;
|
||||
import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.operation.Inverse;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.Polynomial;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRoot;
|
||||
import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRootSolver;
|
||||
import com.numericalmethod.suanshu.number.complex.Complex;
|
||||
|
||||
class SuanShuMath {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SuanShuMath.class);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SuanShuMath math = new SuanShuMath();
|
||||
|
||||
math.addingVectors();
|
||||
math.scaleVector();
|
||||
math.innerProductVectors();
|
||||
math.addingIncorrectVectors();
|
||||
|
||||
math.addingMatrices();
|
||||
math.multiplyMatrices();
|
||||
math.multiplyIncorrectMatrices();
|
||||
math.inverseMatrix();
|
||||
|
||||
Polynomial p = math.createPolynomial();
|
||||
math.evaluatePolynomial(p);
|
||||
math.solvePolynomial();
|
||||
}
|
||||
|
||||
public void addingVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
|
||||
Vector v3 = v1.add(v2);
|
||||
log.info("Adding vectors: {}", v3);
|
||||
}
|
||||
|
||||
public void scaleVector() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = v1.scaled(2.0);
|
||||
log.info("Scaling a vector: {}", v2);
|
||||
}
|
||||
|
||||
public void innerProductVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1});
|
||||
double inner = v1.innerProduct(v2);
|
||||
log.info("Vector inner product: {}", inner);
|
||||
}
|
||||
|
||||
public void addingIncorrectVectors() throws Exception {
|
||||
Vector v1 = new DenseVector(new double[]{1, 2, 3});
|
||||
Vector v2 = new DenseVector(new double[]{5, 4});
|
||||
Vector v3 = v1.add(v2);
|
||||
log.info("Adding vectors: {}", v3);
|
||||
}
|
||||
|
||||
public void addingMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{3, 2, 1},
|
||||
{6, 5, 4}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.add(m2);
|
||||
log.info("Adding matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void multiplyMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{1, 4},
|
||||
{2, 5},
|
||||
{3, 6}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.multiply(m2);
|
||||
log.info("Multiplying matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void multiplyIncorrectMatrices() throws Exception {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
});
|
||||
|
||||
Matrix m2 = new DenseMatrix(new double[][]{
|
||||
{3, 2, 1},
|
||||
{6, 5, 4}
|
||||
});
|
||||
|
||||
Matrix m3 = m1.multiply(m2);
|
||||
log.info("Multiplying matrices: {}", m3);
|
||||
}
|
||||
|
||||
public void inverseMatrix() {
|
||||
Matrix m1 = new DenseMatrix(new double[][]{
|
||||
{1, 2},
|
||||
{3, 4}
|
||||
});
|
||||
|
||||
Inverse m2 = new Inverse(m1);
|
||||
log.info("Inverting a matrix: {}", m2);
|
||||
log.info("Verifying a matrix inverse: {}", m1.multiply(m2));
|
||||
}
|
||||
|
||||
public Polynomial createPolynomial() {
|
||||
return new Polynomial(new double[]{3, -5, 1});
|
||||
}
|
||||
|
||||
public void evaluatePolynomial(Polynomial p) {
|
||||
// Evaluate using a real number
|
||||
log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5));
|
||||
// Evaluate using a complex number
|
||||
log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2)));
|
||||
}
|
||||
|
||||
public void solvePolynomial() {
|
||||
Polynomial p = new Polynomial(new double[]{2, 2, -4});
|
||||
PolyRootSolver solver = new PolyRoot();
|
||||
List<? extends Number> roots = solver.solve(p);
|
||||
log.info("Finding polynomial roots: {}", roots);
|
||||
}
|
||||
|
||||
}
|
|
@ -59,6 +59,7 @@
|
|||
</goals>
|
||||
<configuration>
|
||||
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
|
||||
<outputDirectory>${project.build.directory}/delombok</outputDirectory>
|
||||
<addOutputDirectory>false</addOutputDirectory>
|
||||
<formatPreferences>
|
||||
<javaLangAsFQN>skip</javaLangAsFQN>
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.lombok.builder.defaultvalue;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder(toBuilder = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Pojo {
|
||||
private String name = "foo";
|
||||
private boolean original = true;
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.lombok.builder.defaultvalue;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BuilderWithDefaultValueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBuilderWithDefaultValue_ThanDefaultValueIsPresent() {
|
||||
Pojo build = new Pojo().toBuilder()
|
||||
.build();
|
||||
Assert.assertEquals("foo", build.getName());
|
||||
Assert.assertTrue(build.isOriginal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBuilderWithDefaultValue_NoArgsWorksAlso() {
|
||||
Pojo build = new Pojo().toBuilder()
|
||||
.build();
|
||||
Pojo pojo = new Pojo();
|
||||
Assert.assertEquals(build.getName(), pojo.getName());
|
||||
Assert.assertTrue(build.isOriginal() == pojo.isOriginal());
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
||||
|
|
6
pom.xml
6
pom.xml
|
@ -378,6 +378,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>
|
||||
|
@ -457,7 +458,6 @@
|
|||
<module>spring-5</module>
|
||||
<module>spring-5-data-reactive</module>
|
||||
<module>spring-5-reactive</module>
|
||||
<module>spring-data-5-reactive/spring-5-data-reactive-redis</module>
|
||||
<module>spring-5-reactive-security</module>
|
||||
<module>spring-5-reactive-client</module>
|
||||
<module>spring-5-mvc</module>
|
||||
|
@ -482,6 +482,7 @@
|
|||
<module>spring-boot-mvc</module>
|
||||
<module>spring-boot-vue</module>
|
||||
<module>spring-boot-logging-log4j2</module>
|
||||
<module>spring-boot-disable-console-logging</module>
|
||||
<module>spring-cloud-data-flow</module>
|
||||
<module>spring-cloud</module>
|
||||
<module>spring-cloud-bus</module>
|
||||
|
@ -1024,6 +1025,7 @@
|
|||
<module>spring-boot-security</module>
|
||||
<module>spring-boot-mvc</module>
|
||||
<module>spring-boot-logging-log4j2</module>
|
||||
<module>spring-boot-disable-console-logging</module>
|
||||
<module>spring-cloud-data-flow</module>
|
||||
<module>spring-cloud</module>
|
||||
<module>spring-cloud-bus</module>
|
||||
|
@ -1285,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>
|
||||
|
@ -1379,6 +1382,7 @@
|
|||
<module>spring-boot-security</module>
|
||||
<module>spring-boot-mvc</module>
|
||||
<module>spring-boot-logging-log4j2</module>
|
||||
<module>spring-boot-disable-console-logging</module>
|
||||
<module>spring-cloud-data-flow</module>
|
||||
<module>spring-cloud</module>
|
||||
<module>spring-cloud-bus</module>
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.reactor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ItemProducerCreate {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class);
|
||||
|
||||
Consumer<List<String>> listener;
|
||||
|
||||
public void create() {
|
||||
Flux<String> articlesFlux = Flux.create((sink) -> {
|
||||
ItemProducerCreate.this.listener = (items) -> {
|
||||
items.stream()
|
||||
.forEach(article -> sink.next(article));
|
||||
};
|
||||
});
|
||||
articlesFlux.subscribe(ItemProducerCreate.this.logger::info);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ItemProducerCreate producer = new ItemProducerCreate();
|
||||
producer.create();
|
||||
|
||||
new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
List<String> items = new ArrayList<>();
|
||||
items.add("Item 1");
|
||||
items.add("Item 2");
|
||||
items.add("Item 3");
|
||||
producer.listener.accept(items);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.reactor;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink.OverflowStrategy;
|
||||
|
||||
public class NetworTrafficProducerPush {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class);
|
||||
|
||||
Consumer<String> listener;
|
||||
|
||||
public void subscribe(Consumer<String> consumer) {
|
||||
Flux<String> flux = Flux.push(sink -> {
|
||||
NetworTrafficProducerPush.this.listener = (t) -> sink.next(t);
|
||||
}, OverflowStrategy.DROP);
|
||||
flux.subscribe(consumer);
|
||||
}
|
||||
|
||||
public void onPacket(String packet) {
|
||||
listener.accept(packet);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
NetworTrafficProducerPush trafficProducer = new NetworTrafficProducerPush();
|
||||
trafficProducer.subscribe(trafficProducer.logger::info);
|
||||
trafficProducer.onPacket("Packet[A18]");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.reactor;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ProgramaticSequences {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(ProgramaticSequences.class);
|
||||
|
||||
public void statefullImutableGenerate() {
|
||||
Flux<String> flux = Flux.generate(() -> 1, (state, sink) -> {
|
||||
sink.next("2 + " + state + " = " + 2 + state);
|
||||
if (state == 101)
|
||||
sink.complete();
|
||||
return state + 1;
|
||||
});
|
||||
|
||||
flux.subscribe(logger::info);
|
||||
}
|
||||
|
||||
public void statefullMutableGenerate() {
|
||||
Flux<String> flux = Flux.generate(AtomicInteger::new, (state, sink) -> {
|
||||
int i = state.getAndIncrement();
|
||||
sink.next("2 + " + state + " = " + 2 + state);
|
||||
if (i == 101)
|
||||
sink.complete();
|
||||
return state;
|
||||
});
|
||||
|
||||
flux.subscribe(logger::info);
|
||||
}
|
||||
|
||||
public void handle() {
|
||||
Flux<String> elephants = Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
.handle((i, sink) -> {
|
||||
String animal = "Elephant nr " + i;
|
||||
if (i % 2 == 0) {
|
||||
sink.next(animal);
|
||||
}
|
||||
});
|
||||
|
||||
elephants.subscribe(logger::info);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ProgramaticSequences ps = new ProgramaticSequences();
|
||||
|
||||
ps.statefullImutableGenerate();
|
||||
ps.statefullMutableGenerate();
|
||||
ps.handle();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.reactor;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class StatelessGenerate {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(StatelessGenerate.class);
|
||||
|
||||
public void statelessGenerate() {
|
||||
Flux<String> flux = Flux.generate((sink) -> {
|
||||
sink.next("hallo");
|
||||
});
|
||||
flux.subscribe(logger::info);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
StatelessGenerate ps = new StatelessGenerate();
|
||||
ps.statelessGenerate();
|
||||
}
|
||||
|
||||
}
|
|
@ -15,7 +15,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
|
|||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import com.baeldung.reactive.actuator.Spring5ReactiveApplication;
|
||||
import com.baeldung.webflux.EmployeeSpringApplication;
|
||||
import com.baeldung.webflux.Employee;
|
||||
import com.baeldung.webflux.EmployeeRepository;
|
||||
|
||||
|
@ -23,7 +23,7 @@ import reactor.core.publisher.Flux;
|
|||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=EmployeeSpringApplication.class)
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
public class EmployeeControllerIntegrationTest {
|
||||
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging)
|
|
@ -3,10 +3,12 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>disabling-console-jul</artifactId>
|
||||
|
||||
<!-- this needs to use the boot parent directly in order to not inherit logback dependencies -->
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>disabling-console-logging</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.5.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -3,10 +3,12 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>disabling-console-log4j2</artifactId>
|
||||
|
||||
<!-- this needs to use the boot parent directly in order to not inherit logback dependencies -->
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>disabling-console-logging</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.5.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -2,8 +2,16 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>disabling-console-logging</artifactId>
|
||||
<artifactId>spring-boot-disable-console-logging</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>disabling-console-logback</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue