Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
3b3a0fcd67
25
README.md
25
README.md
@ -1,12 +1,16 @@
|
||||
|
||||
The "REST with Spring" Classes
|
||||
The Courses
|
||||
==============================
|
||||
|
||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
Here's the new "Learn Spring" course: <br/>
|
||||
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
|
||||
|
||||
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of "Learn Spring Security": <br/>
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
@ -15,7 +19,7 @@ Java and Spring Tutorials
|
||||
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
In additional to Spring, the modules here are covering a number of aspects in Java.
|
||||
|
||||
|
||||
Building the project
|
||||
@ -32,8 +36,15 @@ Running a Spring Boot module
|
||||
====================
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||
|
||||
###Running Tests
|
||||
|
||||
Working with the IDE
|
||||
====================
|
||||
This repo contains a large number of modules.
|
||||
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
|
||||
|
||||
|
||||
Running Tests
|
||||
=============
|
||||
The command `mvn clean install` will run the unit tests in a module.
|
||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public final class NaturalOrderComparators {
|
||||
|
||||
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
|
||||
|
||||
private NaturalOrderComparators() {
|
||||
throw new AssertionError("Let's keep this static");
|
||||
}
|
||||
|
||||
public static Comparator<String> createNaturalOrderRegexComparator() {
|
||||
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
|
||||
}
|
||||
|
||||
private static double parseStringToNumber(String input){
|
||||
|
||||
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
|
||||
|
||||
if("".equals(digitsOnly)) return 0;
|
||||
|
||||
try{
|
||||
return Double.parseDouble(digitsOnly);
|
||||
}catch (NumberFormatException nfe){
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
|
||||
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NaturalOrderComparatorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
|
||||
|
||||
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
|
||||
List<String> expected = new ArrayList<>(testStrings);
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
|
||||
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
||||
|
25
core-java-modules/core-java-arrays-2/.gitignore
vendored
Normal file
25
core-java-modules/core-java-arrays-2/.gitignore
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
50
core-java-modules/core-java-arrays-2/pom.xml
Normal file
50
core-java-modules/core-java-arrays-2/pom.xml
Normal file
@ -0,0 +1,50 @@
|
||||
<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>core-java-arrays-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-arrays-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<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-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-arrays-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -4,7 +4,7 @@ import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LoopDiagonallyTest {
|
||||
public class LoopDiagonallyUnitTest {
|
||||
|
||||
@Test
|
||||
public void twoArrayIsLoopedDiagonallyAsExpected() {
|
@ -2,7 +2,10 @@ package com.baeldung.array;
|
||||
|
||||
import com.baeldung.arraycopy.model.Employee;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class SortedArrayChecker {
|
||||
|
||||
boolean isSorted(int[] array, int length) {
|
||||
if (array == null || length < 2)
|
||||
return true;
|
||||
@ -22,7 +25,7 @@ public class SortedArrayChecker {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isSorted(String[] array, int length) {
|
||||
boolean isSorted(Comparable[] array, int length) {
|
||||
if (array == null || length < 2)
|
||||
return true;
|
||||
|
||||
@ -32,40 +35,31 @@ public class SortedArrayChecker {
|
||||
return isSorted(array, length - 1);
|
||||
}
|
||||
|
||||
boolean isSorted(String[] array) {
|
||||
for (int i = 0; i < array.length - 1; ++i) {
|
||||
if (array[i].compareTo(array[i + 1]) > 0)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isSortedByName(Employee[] array) {
|
||||
boolean isSorted(Comparable[] array) {
|
||||
for (int i = 0; i < array.length - 1; ++i) {
|
||||
if (array[i].getName().compareTo(array[i + 1].getName()) > 0)
|
||||
if (array[i].compareTo(array[i + 1]) > 0)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isSortedByAge(Employee[] array) {
|
||||
for (int i = 0; i < array.length - 1; ++i) {
|
||||
if (array[i].getAge() > (array[i + 1].getAge()))
|
||||
return false;
|
||||
boolean isSorted(Object[] array, Comparator comparator) {
|
||||
for (int i = 0; i < array.length - 1; ++i) {
|
||||
if (comparator.compare(array[i], (array[i + 1])) > 0)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean isSortedByAge(Employee[] array, int length) {
|
||||
boolean isSorted(Object[] array, Comparator comparator, int length) {
|
||||
if (array == null || length < 2)
|
||||
return true;
|
||||
|
||||
if (array[length - 2].getAge() > array[length - 1].getAge())
|
||||
if (comparator.compare(array[length - 2], array[length - 1]) > 0)
|
||||
return false;
|
||||
|
||||
return isSortedByAge(array, length - 1);
|
||||
return isSorted(array, comparator, length - 1);
|
||||
}
|
||||
}
|
||||
|
@ -4,32 +4,33 @@ import com.baeldung.arraycopy.model.Employee;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SortedArrayCheckerUnitTest {
|
||||
|
||||
public class SortedArrayCheckerUnitTest {
|
||||
private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9};
|
||||
private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7};
|
||||
|
||||
private static final String[] STRING_SORTED = {"abc", "cde", "fgh"};
|
||||
private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"};
|
||||
|
||||
private final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
||||
private static final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
||||
new Employee(1, "Carlos", 26),
|
||||
new Employee(2, "Daniel", 31),
|
||||
new Employee(3, "Marta", 27)};
|
||||
|
||||
private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
||||
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
||||
new Employee(1, "Daniel", 31),
|
||||
new Employee(2, "Carlos", 26),
|
||||
new Employee(3, "Marta", 27)};
|
||||
|
||||
private final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
||||
private static final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
||||
new Employee(1, "Carlos", 26),
|
||||
new Employee(2, "Marta", 27),
|
||||
new Employee(3, "Daniel", 31)};
|
||||
|
||||
private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
|
||||
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
|
||||
new Employee(1, "Marta", 27),
|
||||
new Employee(2, "Carlos", 26),
|
||||
new Employee(3, "Daniel", 31)};
|
||||
@ -61,13 +62,18 @@ class SortedArrayCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
|
||||
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true);
|
||||
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false);
|
||||
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true);
|
||||
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false);
|
||||
|
||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true);
|
||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false);
|
||||
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true);
|
||||
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(false);
|
||||
|
||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true);
|
||||
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false);
|
||||
assertThat(sortedArrayChecker
|
||||
.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length))
|
||||
.isEqualTo(true);
|
||||
assertThat(sortedArrayChecker
|
||||
.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_NOT_SORTED_BY_AGE.length))
|
||||
.isEqualTo(false);
|
||||
}
|
||||
|
||||
}
|
@ -1,3 +1,3 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
||||
|
25
core-java-modules/core-java-networking-2/.gitignore
vendored
Normal file
25
core-java-modules/core-java-networking-2/.gitignore
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
20
core-java-modules/core-java-networking-2/pom.xml
Normal file
20
core-java-modules/core-java-networking-2/pom.xml
Normal file
@ -0,0 +1,20 @@
|
||||
<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>core-java-networking-2</artifactId>
|
||||
<name>core-java-networking-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-networking-2</finalName>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.url;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class UrlChecker {
|
||||
|
||||
public int getResponseCodeForURL(String address) throws IOException {
|
||||
return getResponseCodeForURLUsing(address, "GET");
|
||||
}
|
||||
|
||||
public int getResponseCodeForURLUsingHead(String address) throws IOException {
|
||||
return getResponseCodeForURLUsing(address, "HEAD");
|
||||
}
|
||||
|
||||
private int getResponseCodeForURLUsing(String address, String method) throws IOException {
|
||||
HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false
|
||||
final URL url = new URL(address);
|
||||
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
|
||||
huc.setRequestMethod(method);
|
||||
return huc.getResponseCode();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.url;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UrlCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
}
|
3
core-java-modules/multimodulemavenproject/README.md
Normal file
3
core-java-modules/multimodulemavenproject/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
@ -17,6 +17,7 @@
|
||||
<module>pre-jpms</module>
|
||||
<module>core-java-exceptions</module>
|
||||
<module>core-java-optional</module>
|
||||
<module>core-java-networking-2</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
72
data-structures/src/main/java/com/baeldung/graph/Graph.java
Normal file
72
data-structures/src/main/java/com/baeldung/graph/Graph.java
Normal file
@ -0,0 +1,72 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private Map<Integer, List<Integer>> adjVertices;
|
||||
|
||||
public Graph() {
|
||||
this.adjVertices = new HashMap<Integer, List<Integer>>();
|
||||
}
|
||||
|
||||
public void addVertex(int vertex) {
|
||||
adjVertices.putIfAbsent(vertex, new ArrayList<>());
|
||||
}
|
||||
|
||||
public void addEdge(int src, int dest) {
|
||||
adjVertices.get(src).add(dest);
|
||||
}
|
||||
|
||||
public void dfsWithoutRecursion(int start) {
|
||||
Stack<Integer> stack = new Stack<Integer>();
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
stack.push(start);
|
||||
while (!stack.isEmpty()) {
|
||||
int current = stack.pop();
|
||||
isVisited[current] = true;
|
||||
System.out.print(" " + current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
stack.push(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void dfs(int start) {
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
dfsRecursive(start, isVisited);
|
||||
}
|
||||
|
||||
private void dfsRecursive(int current, boolean[] isVisited) {
|
||||
isVisited[current] = true;
|
||||
System.out.print(" " + current);
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
dfsRecursive(dest, isVisited);
|
||||
}
|
||||
}
|
||||
|
||||
public void topologicalSort(int start) {
|
||||
Stack<Integer> result = new Stack<Integer>();
|
||||
boolean[] isVisited = new boolean[adjVertices.size()];
|
||||
topologicalSortRecursive(start, isVisited, result);
|
||||
while (!result.isEmpty()) {
|
||||
System.out.print(" " + result.pop());
|
||||
}
|
||||
}
|
||||
|
||||
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
|
||||
isVisited[current] = true;
|
||||
for (int dest : adjVertices.get(current)) {
|
||||
if (!isVisited[dest])
|
||||
topologicalSortRecursive(dest, isVisited, result);
|
||||
}
|
||||
result.push(current);
|
||||
}
|
||||
|
||||
}
|
@ -2,6 +2,7 @@ package com.baeldung.tree;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Stack;
|
||||
|
||||
public class BinaryTree {
|
||||
|
||||
@ -147,6 +148,68 @@ public class BinaryTree {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
|
||||
if(current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if(current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
current = stack.peek();
|
||||
boolean hasChild = (current.left != null || current.right != null);
|
||||
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||
|
||||
if (!hasChild || isPrevLastChild) {
|
||||
current = stack.pop();
|
||||
System.out.print(" " + current.value);
|
||||
prev = current;
|
||||
} else {
|
||||
if (current.right != null) {
|
||||
stack.push(current.right);
|
||||
}
|
||||
if (current.left != null) {
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
|
||||
Graph graph = createDirectedGraph();
|
||||
graph.dfs(0);
|
||||
System.out.println();
|
||||
graph.dfsWithoutRecursion(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
|
||||
Graph graph = createDirectedGraph();
|
||||
graph.topologicalSort(0);
|
||||
}
|
||||
|
||||
private Graph createDirectedGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex(0);
|
||||
graph.addVertex(1);
|
||||
graph.addVertex(2);
|
||||
graph.addVertex(3);
|
||||
graph.addVertex(4);
|
||||
graph.addVertex(5);
|
||||
graph.addEdge(0, 1);
|
||||
graph.addEdge(0, 2);
|
||||
graph.addEdge(1, 3);
|
||||
graph.addEdge(2, 3);
|
||||
graph.addEdge(3, 4);
|
||||
graph.addEdge(4, 5);
|
||||
return graph;
|
||||
}
|
||||
}
|
@ -87,6 +87,8 @@ public class BinaryTreeUnitTest {
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -95,6 +97,8 @@ public class BinaryTreeUnitTest {
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -103,6 +107,8 @@ public class BinaryTreeUnitTest {
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToLowerCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignUppercase = "\u0049";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
|
||||
assertEquals("john doe", name.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0069", foreignUppercase.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToUpperCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignLowercase = "\u0069";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
|
||||
assertEquals("JOHN DOE", name.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0049", foreignLowercase.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
import javax.validation.constraints.Digits;
|
||||
|
||||
public class Invoice {
|
||||
|
||||
@DecimalMin(value = "0.0", inclusive = false)
|
||||
@Digits(integer=3, fraction=2)
|
||||
private BigDecimal price;
|
||||
private String description;
|
||||
|
||||
public Invoice(BigDecimal price, String description) {
|
||||
this.price = price;
|
||||
this.description = description;
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package org.baeldung.javabeanconstraints.bigdecimal;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InvoiceUnitTest {
|
||||
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIsZero_thenShouldGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() {
|
||||
Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased");
|
||||
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
}
|
3
jhipster/jhipster-microservice/README.md
Normal file
3
jhipster/jhipster-microservice/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices)
|
@ -1,4 +1,6 @@
|
||||
### Relevant articles
|
||||
## Relevant Articles
|
||||
|
||||
- [Intro to JHipster](https://www.baeldung.com/jhipster)
|
||||
|
||||
|
||||
# baeldung
|
||||
|
3
jhipster/jhipster-uaa/README.md
Normal file
3
jhipster/jhipster-uaa/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
|
@ -121,8 +121,8 @@ public class AuthorizationEndpoint {
|
||||
String redirectUri = originalParams.getFirst("resolved_redirect_uri");
|
||||
StringBuilder sb = new StringBuilder(redirectUri);
|
||||
|
||||
String approbationStatus = params.getFirst("approbation_status");
|
||||
if ("NO".equals(approbationStatus)) {
|
||||
String approvalStatus = params.getFirst("approval_status");
|
||||
if ("NO".equals(approvalStatus)) {
|
||||
URI location = UriBuilder.fromUri(sb.toString())
|
||||
.queryParam("error", "User doesn't approved the request.")
|
||||
.queryParam("error_description", "User doesn't approved the request.")
|
||||
|
@ -15,15 +15,14 @@ import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Path("token")
|
||||
public class TokenEndpoint {
|
||||
|
||||
List<String> supportedGrantTypes = Collections.singletonList("authorization_code");
|
||||
List<String> supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
|
||||
|
||||
@Inject
|
||||
private AppDataRepository appDataRepository;
|
||||
@ -39,36 +38,36 @@ public class TokenEndpoint {
|
||||
|
||||
//Check grant_type params
|
||||
String grantType = params.getFirst("grant_type");
|
||||
Objects.requireNonNull(grantType, "grant_type params is required");
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "unsupported_grant_type")
|
||||
.add("error_description", "grant type should be one of :" + supportedGrantTypes)
|
||||
.build();
|
||||
return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(error).build();
|
||||
if (grantType == null || grantType.isEmpty())
|
||||
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
|
||||
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
//Client Authentication
|
||||
String[] clientCredentials = extract(authHeader);
|
||||
if (clientCredentials.length != 2) {
|
||||
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientId = clientCredentials[0];
|
||||
String clientSecret = clientCredentials[1];
|
||||
Client client = appDataRepository.getClient(clientId);
|
||||
if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "invalid_client")
|
||||
.build();
|
||||
return Response.status(Response.Status.UNAUTHORIZED)
|
||||
.entity(error).build();
|
||||
if (client == null) {
|
||||
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientSecret = clientCredentials[1];
|
||||
if (!clientSecret.equals(client.getClientSecret())) {
|
||||
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
|
||||
JsonObject tokenResponse = null;
|
||||
try {
|
||||
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
|
||||
} catch (WebApplicationException e) {
|
||||
return e.getResponse();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return Response.ok(tokenResponse)
|
||||
@ -81,6 +80,15 @@ public class TokenEndpoint {
|
||||
if (authHeader != null && authHeader.startsWith("Basic ")) {
|
||||
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
|
||||
}
|
||||
return null;
|
||||
return new String[]{};
|
||||
}
|
||||
|
||||
private Response responseError(String error, String errorDescription, Response.Status status) {
|
||||
JsonObject errorResponse = Json.createObjectBuilder()
|
||||
.add("error", error)
|
||||
.add("error_description", errorDescription)
|
||||
.build();
|
||||
return Response.status(status)
|
||||
.entity(errorResponse).build();
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,87 @@
|
||||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||
import com.nimbusds.jose.*;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||
|
||||
//Always RSA 256, but could be parametrized
|
||||
protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||
|
||||
@Inject
|
||||
protected Config config;
|
||||
|
||||
//30 min
|
||||
protected Long expiresInMin = 30L;
|
||||
|
||||
protected JWSVerifier getJWSVerifier() throws Exception {
|
||||
String verificationkey = config.getValue("verificationkey", String.class);
|
||||
String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
|
||||
RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
|
||||
return new RSASSAVerifier(rsaPublicKey);
|
||||
}
|
||||
|
||||
protected JWSSigner getJwsSigner() throws Exception {
|
||||
String signingkey = config.getValue("signingkey", String.class);
|
||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||
return new RSASSASigner(rsaKey.toRSAPrivateKey());
|
||||
}
|
||||
|
||||
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||
//4. Signing
|
||||
JWSSigner jwsSigner = getJwsSigner();
|
||||
|
||||
Instant now = Instant.now();
|
||||
//Long expiresInMin = 30L;
|
||||
Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||
|
||||
//3. JWT Payload or claims
|
||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||
.issuer("http://localhost:9080")
|
||||
.subject(subject)
|
||||
.claim("upn", subject)
|
||||
.claim("client_id", clientId)
|
||||
.audience("http://localhost:9280")
|
||||
.claim("scope", approvedScope)
|
||||
.claim("groups", Arrays.asList(approvedScope.split(" ")))
|
||||
.expirationTime(expirationTime) // expires in 30 minutes
|
||||
.notBeforeTime(Date.from(now))
|
||||
.issueTime(Date.from(now))
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||
signedJWT.sign(jwsSigner);
|
||||
return signedJWT.serialize();
|
||||
}
|
||||
|
||||
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception {
|
||||
JWSSigner jwsSigner = getJwsSigner();
|
||||
Instant now = Instant.now();
|
||||
//6.Build refresh token
|
||||
JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder()
|
||||
.subject(subject)
|
||||
.claim("client_id", clientId)
|
||||
.claim("scope", approvedScope)
|
||||
//refresh token for 1 day.
|
||||
.expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS)))
|
||||
.build();
|
||||
SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims);
|
||||
signedRefreshToken.sign(jwsSigner);
|
||||
return signedRefreshToken.serialize();
|
||||
}
|
||||
}
|
@ -1,18 +1,7 @@
|
||||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
|
||||
import com.nimbusds.jose.JOSEObjectType;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.JWSHeader;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
@ -20,22 +9,14 @@ import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Named("authorization_code")
|
||||
public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||
public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
//1. code is required
|
||||
@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType
|
||||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//JWT Header
|
||||
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||
|
||||
Instant now = Instant.now();
|
||||
Long expiresInMin = 30L;
|
||||
Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||
|
||||
//3. JWT Payload or claims
|
||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||
.issuer("http://localhost:9080")
|
||||
.subject(authorizationCode.getUserId())
|
||||
.claim("upn", authorizationCode.getUserId())
|
||||
.audience("http://localhost:9280")
|
||||
.claim("scope", authorizationCode.getApprovedScopes())
|
||||
.claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" ")))
|
||||
.expirationTime(expiresIn) // expires in 30 minutes
|
||||
.notBeforeTime(Date.from(now))
|
||||
.issueTime(Date.from(now))
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||
|
||||
//4. Signing
|
||||
String signingkey = config.getValue("signingkey", String.class);
|
||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||
signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey()));
|
||||
|
||||
//5. Finally the JWT access token
|
||||
String accessToken = signedJWT.serialize();
|
||||
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", authorizationCode.getApprovedScopes())
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,72 @@
|
||||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Named("refresh_token")
|
||||
public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
String refreshToken = params.getFirst("refresh_token");
|
||||
if (refreshToken == null || "".equals(refreshToken)) {
|
||||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//Decode refresh token
|
||||
SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
|
||||
JWSVerifier verifier = getJWSVerifier();
|
||||
|
||||
if (!signedRefreshToken.verify(verifier)) {
|
||||
throw new WebApplicationException("Invalid refresh token.");
|
||||
}
|
||||
if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
|
||||
throw new WebApplicationException("Refresh token expired.");
|
||||
}
|
||||
String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
|
||||
if (!clientId.equals(refreshTokenClientId)) {
|
||||
throw new WebApplicationException("Invalid client_id.");
|
||||
}
|
||||
|
||||
//At this point, the refresh token is valid and not yet expired
|
||||
//So create a new access token from it.
|
||||
String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
|
||||
String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");
|
||||
|
||||
String requestedScopes = params.getFirst("scope");
|
||||
if (requestedScopes != null && !requestedScopes.isEmpty()) {
|
||||
Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
|
||||
Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
|
||||
if (!aScopes.containsAll(rScopes)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "Invalid_request")
|
||||
.add("error_description", "Requested scopes should be a subset of the original scopes.")
|
||||
.build();
|
||||
Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
|
||||
throw new WebApplicationException(response);
|
||||
}
|
||||
} else {
|
||||
requestedScopes = approvedScopes;
|
||||
}
|
||||
|
||||
String accessToken = getAccessToken(clientId, subject, requestedScopes);
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", requestedScopes)
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
@ -41,8 +41,8 @@
|
||||
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<input type="submit" name="approbation_status" value="YES"/>
|
||||
<input type="submit" name="approbation_status" value="NO"/>
|
||||
<input type="submit" name="approval_status" value="YES"/>
|
||||
<input type="submit" name="approval_status" value="NO"/>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.oauth2.client;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
public abstract class AbstractServlet extends HttpServlet {
|
||||
|
||||
protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
||||
requestDispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
protected String getAuthorizationHeaderValue(String clientId, String clientSecret) {
|
||||
String token = clientId + ":" + clientSecret;
|
||||
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
||||
return "Basic " + encodedString;
|
||||
}
|
||||
}
|
@ -4,10 +4,8 @@ import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.json.JsonObject;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.client.Client;
|
||||
@ -18,10 +16,9 @@ import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
@WebServlet(urlPatterns = "/callback")
|
||||
public class CallbackServlet extends HttpServlet {
|
||||
public class CallbackServlet extends AbstractServlet {
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
@ -29,6 +26,9 @@ public class CallbackServlet extends HttpServlet {
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
|
||||
//Error:
|
||||
String error = request.getParameter("error");
|
||||
if (error != null) {
|
||||
@ -53,24 +53,15 @@ public class CallbackServlet extends HttpServlet {
|
||||
form.param("code", code);
|
||||
form.param("redirect_uri", config.getValue("client.redirectUri", String.class));
|
||||
|
||||
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue())
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
||||
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
try {
|
||||
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
} catch (Exception ex) {
|
||||
System.out.println(ex.getMessage());
|
||||
request.setAttribute("error", ex.getMessage());
|
||||
}
|
||||
dispatch("/", request, response);
|
||||
}
|
||||
|
||||
private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
|
||||
requestDispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
private String getAuthorizationHeaderValue() {
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
String token = clientId + ":" + clientSecret;
|
||||
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
|
||||
return "Basic " + encodedString;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.oauth2.client;
|
||||
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.json.JsonObject;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(urlPatterns = "/refreshtoken")
|
||||
public class RefreshTokenServlet extends AbstractServlet {
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
String clientId = config.getValue("client.clientId", String.class);
|
||||
String clientSecret = config.getValue("client.clientSecret", String.class);
|
||||
|
||||
JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse");
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget target = client.target(config.getValue("provider.tokenUri", String.class));
|
||||
|
||||
Form form = new Form();
|
||||
form.param("grant_type", "refresh_token");
|
||||
form.param("refresh_token", actualTokenResponse.getString("refresh_token"));
|
||||
|
||||
String scope = request.getParameter("scope");
|
||||
if (scope != null && !scope.isEmpty()) {
|
||||
form.param("scope", scope);
|
||||
}
|
||||
|
||||
Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
|
||||
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
|
||||
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
|
||||
JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class);
|
||||
if (jaxrsResponse.getStatus() == 200) {
|
||||
request.getSession().setAttribute("tokenResponse", tokenResponse);
|
||||
} else {
|
||||
request.setAttribute("error", tokenResponse.getString("error_description", "error!"));
|
||||
}
|
||||
dispatch("/", request, response);
|
||||
}
|
||||
}
|
@ -10,6 +10,7 @@
|
||||
body {
|
||||
margin: 0px;
|
||||
}
|
||||
|
||||
input[type=text], input[type=password] {
|
||||
width: 75%;
|
||||
padding: 4px 0px;
|
||||
@ -17,6 +18,7 @@
|
||||
border: 1px solid #502bcc;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.container-error {
|
||||
padding: 16px;
|
||||
border: 1px solid #cc102a;
|
||||
@ -25,6 +27,7 @@
|
||||
margin-left: 25px;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 16px;
|
||||
border: 1px solid #130ecc;
|
||||
@ -81,8 +84,20 @@
|
||||
<li>access_token: ${tokenResponse.getString("access_token")}</li>
|
||||
<li>scope: ${tokenResponse.getString("scope")}</li>
|
||||
<li>Expires in (s): ${tokenResponse.getInt("expires_in")}</li>
|
||||
<li>refresh_token: ${tokenResponse.getString("refresh_token")}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<span><h4>Refresh Token</h4></span>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="refreshtoken">Refresh token (original scope)</a></li>
|
||||
<li><a href="refreshtoken?scope=resource.read">Refresh token (scope: resource.read)</a></li>
|
||||
<li><a href="refreshtoken?scope=resource.write">Refresh token (scope: resource.write)</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<span><h4>OAuth2 Resource Server Call</h4></span>
|
||||
<hr>
|
||||
@ -90,7 +105,6 @@
|
||||
<li><a href="downstream?action=read">Read Protected Resource</a></li>
|
||||
<li><a href="downstream?action=write">Write Protected Resource</a></li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
|
||||
</body>
|
||||
|
@ -1 +0,0 @@
|
||||
This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features.
|
@ -1,92 +0,0 @@
|
||||
<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>parent-boot-performance</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>parent-boot-performance</name>
|
||||
<packaging>pom</packaging>
|
||||
<description>Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<configuration>
|
||||
<mainClass>${start-class}</mainClass>
|
||||
<!-- this is necessary as we're not using the Boot parent -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>thin-jar</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<dependencies>
|
||||
<!-- The following enables the "thin jar" deployment option. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot.experimental</groupId>
|
||||
<artifactId>spring-boot-thin-layout</artifactId>
|
||||
<version>${thin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<rest-assured.version>3.1.0</rest-assured.version>
|
||||
<!-- plugins -->
|
||||
<thin.version>1.0.21.RELEASE</thin.version>
|
||||
<spring-boot.version>2.2.0.M3</spring-boot.version>
|
||||
</properties>
|
||||
</project>
|
@ -1 +1 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
@ -1 +1 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
@ -1 +1 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
@ -2,10 +2,6 @@
|
||||
<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">
|
||||
<artifactId>jpa-hibernate-cascade-type</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
@ -13,6 +9,10 @@
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>jpa-hibernate-cascade-type</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
|
@ -58,5 +58,6 @@
|
||||
<module>spring-jpa</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
<module>jpa-hibernate-cascade-type</module>
|
||||
<module>r2dbc</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
31
persistence-modules/r2dbc/.gitignore
vendored
Normal file
31
persistence-modules/r2dbc/.gitignore
vendored
Normal file
@ -0,0 +1,31 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**
|
||||
!**/src/test/**
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
114
persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
114
persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
@ -0,0 +1,114 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
BIN
persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
BIN
persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.jar
vendored
Normal file
Binary file not shown.
1
persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
1
persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@ -0,0 +1 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
|
3
persistence-modules/r2dbc/README.md
Normal file
3
persistence-modules/r2dbc/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [R2DBC – Reactive Relational Database Connectivity](https://www.baeldung.com/r2dbc)
|
||||
|
286
persistence-modules/r2dbc/mvnw
vendored
Normal file
286
persistence-modules/r2dbc/mvnw
vendored
Normal file
@ -0,0 +1,286 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
curl -o "$wrapperJarPath" "$jarUrl"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
161
persistence-modules/r2dbc/mvnw.cmd
vendored
Normal file
161
persistence-modules/r2dbc/mvnw.cmd
vendored
Normal file
@ -0,0 +1,161 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
echo Found %WRAPPER_JAR%
|
||||
) else (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
90
persistence-modules/r2dbc/pom.xml
Normal file
90
persistence-modules/r2dbc/pom.xml
Normal file
@ -0,0 +1,90 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.6.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>org.baeldung.examples.r2dbc</groupId>
|
||||
<artifactId>r2dbc-example</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>r2dbc-example</name>
|
||||
<description>Sample R2DBC Project</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- R2DBC H2 Driver -->
|
||||
<dependency>
|
||||
<groupId>io.r2dbc</groupId>
|
||||
<artifactId>r2dbc-h2</artifactId>
|
||||
<version>0.8.0.M8</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<!-- Extra repositories for R2DBC-H2 -->
|
||||
<repositories>
|
||||
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
|
||||
</repositories>
|
||||
|
||||
</project>
|
@ -0,0 +1,68 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class Account {
|
||||
|
||||
private Long id;
|
||||
private String iban;
|
||||
private BigDecimal balance;
|
||||
|
||||
|
||||
public Account() {}
|
||||
|
||||
public Account(Long id, String iban, BigDecimal balance) {
|
||||
this.id = id;
|
||||
this.iban = iban;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public Account(Long id, String iban, Double balance) {
|
||||
this.id = id;
|
||||
this.iban = iban;
|
||||
this.balance = new BigDecimal(balance);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the id
|
||||
*/
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param id the id to set
|
||||
*/
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the iban
|
||||
*/
|
||||
public String getIban() {
|
||||
return iban;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param iban the iban to set
|
||||
*/
|
||||
public void setIban(String iban) {
|
||||
this.iban = iban;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the balance
|
||||
*/
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param balance the balance to set
|
||||
*/
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.r2dbc.spi.Connection;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class AccountResource {
|
||||
|
||||
private final ReactiveAccountDao accountDao;
|
||||
|
||||
public AccountResource(ReactiveAccountDao accountDao) {
|
||||
this.accountDao = accountDao;
|
||||
}
|
||||
|
||||
@GetMapping("/accounts/{id}")
|
||||
public Mono<ResponseEntity<Account>> getAccount(@PathVariable("id") Long id) {
|
||||
|
||||
return accountDao.findById(id)
|
||||
.map(acc -> new ResponseEntity<>(acc, HttpStatus.OK))
|
||||
.switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND)));
|
||||
}
|
||||
|
||||
@GetMapping("/accounts")
|
||||
public Flux<Account> getAllAccounts() {
|
||||
return accountDao.findAll();
|
||||
}
|
||||
|
||||
@PostMapping("/accounts")
|
||||
public Mono<ResponseEntity<Account>> postAccount(@RequestBody Account account) {
|
||||
return accountDao.createAccount(account)
|
||||
.map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED))
|
||||
.log();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import io.r2dbc.spi.ConnectionFactories;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import io.r2dbc.spi.ConnectionFactoryOptions;
|
||||
import io.r2dbc.spi.ConnectionFactoryOptions.Builder;
|
||||
import io.r2dbc.spi.Option;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import static io.r2dbc.spi.ConnectionFactoryOptions.*;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class DatasourceConfig {
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
|
||||
|
||||
ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
|
||||
Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
|
||||
if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
|
||||
ob = ob.option(USER, properties.getUser());
|
||||
}
|
||||
|
||||
if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
|
||||
ob = ob.option(PASSWORD, properties.getPassword());
|
||||
}
|
||||
|
||||
ConnectionFactory cf = ConnectionFactories.get(ob.build());
|
||||
return cf;
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public CommandLineRunner initDatabase(ConnectionFactory cf) {
|
||||
|
||||
return (args) ->
|
||||
Flux.from(cf.create())
|
||||
.flatMap(c ->
|
||||
Flux.from(c.createBatch()
|
||||
.add("drop table if exists Account")
|
||||
.add("create table Account(" +
|
||||
"id IDENTITY(1,1)," +
|
||||
"iban varchar(80) not null," +
|
||||
"balance DECIMAL(18,2) not null)")
|
||||
.add("insert into Account(iban,balance)" +
|
||||
"values('BR430120980198201982',100.00)")
|
||||
.add("insert into Account(iban,balance)" +
|
||||
"values('BR430120998729871000',250.00)")
|
||||
.execute())
|
||||
.doFinally((st) -> c.close())
|
||||
)
|
||||
.log()
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,58 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "r2dbc")
|
||||
public class R2DBCConfigurationProperties {
|
||||
|
||||
@NotEmpty
|
||||
private String url;
|
||||
|
||||
private String user;
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* @return the url
|
||||
*/
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param url the url to set
|
||||
*/
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the user
|
||||
*/
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param user the user to set
|
||||
*/
|
||||
public void setUser(String user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the password
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param password the password to set
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties(R2DBCConfigurationProperties.class)
|
||||
public class R2dbcExampleApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(R2dbcExampleApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import io.r2dbc.spi.Connection;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class ReactiveAccountDao {
|
||||
|
||||
private ConnectionFactory connectionFactory;
|
||||
|
||||
public ReactiveAccountDao(ConnectionFactory connectionFactory) {
|
||||
this.connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
public Mono<Account> findById(long id) {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1")
|
||||
.bind("$1", id)
|
||||
.execute())
|
||||
.doFinally((st) -> close(c)))
|
||||
.map(result -> result.map((row, meta) ->
|
||||
new Account(row.get("id", Long.class),
|
||||
row.get("iban", String.class),
|
||||
row.get("balance", BigDecimal.class))))
|
||||
.flatMap( p -> Mono.from(p));
|
||||
}
|
||||
|
||||
public Flux<Account> findAll() {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account")
|
||||
.execute())
|
||||
.doFinally((st) -> close(c)))
|
||||
.flatMapMany(result -> Flux.from(result.map((row, meta) -> {
|
||||
Account acc = new Account();
|
||||
acc.setId(row.get("id", Long.class));
|
||||
acc.setIban(row.get("iban", String.class));
|
||||
acc.setBalance(row.get("balance", BigDecimal.class));
|
||||
return acc;
|
||||
})));
|
||||
}
|
||||
|
||||
public Mono<Account> createAccount(Account account) {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap(c -> Mono.from(c.beginTransaction())
|
||||
.then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)")
|
||||
.bind("$1", account.getIban())
|
||||
.bind("$2", account.getBalance())
|
||||
.returnGeneratedValues("id")
|
||||
.execute()))
|
||||
.map(result -> result.map((row, meta) ->
|
||||
new Account(row.get("id", Long.class),
|
||||
account.getIban(),
|
||||
account.getBalance())))
|
||||
.flatMap(pub -> Mono.from(pub))
|
||||
.delayUntil(r -> c.commitTransaction())
|
||||
.doFinally((st) -> c.close()));
|
||||
|
||||
}
|
||||
|
||||
private <T> Mono<T> close(Connection connection) {
|
||||
return Mono.from(connection.close())
|
||||
.then(Mono.empty());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
{"properties": [{
|
||||
"name": "r2dbc",
|
||||
"type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties",
|
||||
"description": "R2DBC Connection properties"
|
||||
}]}
|
13
persistence-modules/r2dbc/src/main/resources/application.yml
Normal file
13
persistence-modules/r2dbc/src/main/resources/application.yml
Normal file
@ -0,0 +1,13 @@
|
||||
spring:
|
||||
application:
|
||||
name: r2dbc-test
|
||||
|
||||
# R2DBC URL
|
||||
r2dbc:
|
||||
url: r2dbc:h2:mem://./testdb
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -0,0 +1,102 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.core.IsNull;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class R2dbcExampleApplicationTests {
|
||||
|
||||
|
||||
@Autowired
|
||||
private WebTestClient webTestClient;
|
||||
|
||||
@Autowired
|
||||
ConnectionFactory cf;
|
||||
|
||||
@Before
|
||||
public void initDatabase() {
|
||||
|
||||
Flux.from(cf.create())
|
||||
.flatMap(c ->
|
||||
c.createBatch()
|
||||
.add("drop table if exists Account")
|
||||
.add("create table Account(id IDENTITY(1,1), iban varchar(80) not null, balance DECIMAL(18,2) not null)")
|
||||
.add("insert into Account(iban,balance) values ( 'BR430120980198201982', 100.00 ) ")
|
||||
.add("insert into Account(iban,balance) values ( 'BR430120998729871000', 250.00 ) ")
|
||||
.execute()
|
||||
)
|
||||
.log()
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingAccountId_whenGetAccount_thenReturnExistingAccountInfo() {
|
||||
|
||||
webTestClient
|
||||
.get()
|
||||
.uri("/accounts/1")
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(Account.class)
|
||||
.value((acc) -> {
|
||||
assertThat(acc.getId(),is(1l));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatabaseHasSomeAccounts_whenGetAccount_thenReturnExistingAccounts() {
|
||||
|
||||
webTestClient
|
||||
.get()
|
||||
.uri("/accounts")
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(List.class)
|
||||
.value((accounts) -> {
|
||||
assertThat(accounts.size(),not(is(0)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenNewAccountData_whenPostAccount_thenReturnNewAccountInfo() {
|
||||
|
||||
webTestClient
|
||||
.post()
|
||||
.uri("/accounts")
|
||||
.syncBody(new Account(null,"BR4303010298012098", 151.00 ))
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody(Account.class)
|
||||
.value((acc) -> {
|
||||
assertThat(acc.getId(),is(notNullValue()));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
# R2DBC Test configuration
|
||||
r2dbc:
|
||||
url: r2dbc:h2:mem://./testdb
|
||||
|
||||
|
||||
|
@ -10,7 +10,6 @@
|
||||
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
|
||||
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
|
||||
- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories)
|
||||
- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa)
|
||||
- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date)
|
||||
- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd)
|
||||
- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
|
||||
|
@ -10,6 +10,7 @@
|
||||
- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate)
|
||||
- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa)
|
||||
|
||||
### Quick Start
|
||||
|
||||
|
@ -47,7 +47,7 @@ import com.google.common.base.Preconditions;
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
|
||||
@EnableJpaAuditing
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
public class PersistenceConfig {
|
||||
|
||||
|
@ -2,6 +2,7 @@ package com.baeldung.persistence.audit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ -17,6 +18,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
@ -29,6 +31,7 @@ import com.baeldung.spring.config.PersistenceTestConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class EnversFooBarAuditIntegrationTest {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class);
|
||||
|
22
pom.xml
22
pom.xml
@ -392,6 +392,7 @@
|
||||
<!--<module>core-java-modules/core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
||||
<!--<module>core-java-modules/core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
|
||||
<module>core-java-modules/core-java-arrays</module>
|
||||
<module>core-java-modules/core-java-arrays-2</module>
|
||||
<module>core-java-modules/core-java-collections</module>
|
||||
<module>core-java-modules/core-java-collections-list</module>
|
||||
<module>core-java-modules/core-java-collections-list-2</module>
|
||||
@ -482,7 +483,7 @@
|
||||
<module>jee-7</module> -->
|
||||
<module>jee-7-security</module>
|
||||
<module>jersey</module>
|
||||
<module>JGit</module>
|
||||
<module>jgit</module>
|
||||
<module>jgroups</module>
|
||||
<module>jhipster-5</module>
|
||||
<module>jib</module>
|
||||
@ -561,7 +562,7 @@
|
||||
<module>tensorflow-java</module>
|
||||
<module>spring-boot-flowable</module>
|
||||
<module>spring-security-kerberos</module>
|
||||
|
||||
<module>oauth2-framework-impl</module>
|
||||
</modules>
|
||||
|
||||
</profile>
|
||||
@ -614,6 +615,7 @@
|
||||
<module>spring-5-data-reactive</module>
|
||||
<module>spring-5-mvc</module>
|
||||
<module>spring-5-reactive</module>
|
||||
<module>spring-5-reactive-2</module>
|
||||
<module>spring-5-reactive-client</module>
|
||||
<module>spring-5-reactive-oauth</module>
|
||||
<module>spring-5-reactive-security</module>
|
||||
@ -742,7 +744,7 @@
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-openid</module>
|
||||
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->
|
||||
@ -779,7 +781,7 @@
|
||||
<module>testing-modules</module>
|
||||
|
||||
<module>twilio</module>
|
||||
<module>Twitter4J</module>
|
||||
<module>twitter4j</module>
|
||||
|
||||
<module>undertow</module>
|
||||
|
||||
@ -826,6 +828,7 @@
|
||||
<module>spring-5</module>
|
||||
<module>spring-5-data-reactive</module>
|
||||
<module>spring-5-reactive</module>
|
||||
<module>spring-5-reactive-2</module>
|
||||
<module>spring-5-reactive-client</module>
|
||||
<module>spring-5-reactive-security</module>
|
||||
<module>spring-5-security</module>
|
||||
@ -917,7 +920,7 @@
|
||||
<module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-rest</module>
|
||||
<module>spring-security-sso</module>
|
||||
@ -1086,6 +1089,7 @@
|
||||
<!--<module>core-java-modules/core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
|
||||
<!--<module>core-java-modules/core-java-os</module> --> <!-- We haven't upgraded to java 9.-->
|
||||
<module>core-java-modules/core-java-arrays</module>
|
||||
<module>core-java-modules/core-java-arrays-2</module>
|
||||
<module>core-java-modules/core-java-collections</module>
|
||||
<module>core-java-modules/core-java-collections-list</module>
|
||||
<module>core-java-modules/core-java-collections-list-2</module>
|
||||
@ -1172,7 +1176,7 @@
|
||||
<module>jee-7</module> -->
|
||||
<module>jee-7-security</module>
|
||||
<module>jersey</module>
|
||||
<module>JGit</module>
|
||||
<module>jgit</module>
|
||||
<module>jgroups</module>
|
||||
<module>jhipster-5</module>
|
||||
<module>jib</module>
|
||||
@ -1242,6 +1246,7 @@
|
||||
<module>rsocket</module>
|
||||
<module>rxjava</module>
|
||||
<module>rxjava-2</module>
|
||||
<module>oauth2-framework-impl</module>
|
||||
|
||||
</modules>
|
||||
|
||||
@ -1286,6 +1291,7 @@
|
||||
<module>spring-5-data-reactive</module>
|
||||
<module>spring-5-mvc</module>
|
||||
<module>spring-5-reactive</module>
|
||||
<module>spring-5-reactive-2</module>
|
||||
<module>spring-5-reactive-client</module>
|
||||
<module>spring-5-reactive-oauth</module>
|
||||
<module>spring-5-reactive-security</module>
|
||||
@ -1408,7 +1414,7 @@
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
<module>spring-security-mvc-session</module>
|
||||
<module>spring-security-mvc</module>
|
||||
<module>spring-security-mvc-socket</module>
|
||||
<module>spring-security-openid</module>
|
||||
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->
|
||||
@ -1445,7 +1451,7 @@
|
||||
<module>testing-modules</module>
|
||||
|
||||
<module>twilio</module>
|
||||
<module>Twitter4J</module>
|
||||
<module>twitter4j</module>
|
||||
|
||||
<module>undertow</module>
|
||||
|
||||
|
@ -1,3 +1,3 @@
|
||||
## Relevant articles:
|
||||
## Relevant Articles:
|
||||
|
||||
- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io)
|
||||
|
@ -7,7 +7,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
@QuarkusTest
|
||||
public class HelloResourceTest {
|
||||
public class HelloResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void testHelloEndpoint() {
|
@ -3,7 +3,7 @@ package com.baeldung.quarkus;
|
||||
import io.quarkus.test.junit.SubstrateTest;
|
||||
|
||||
@SubstrateTest
|
||||
public class NativeHelloResourceIT extends HelloResourceTest {
|
||||
public class NativeHelloResourceIT extends HelloResourceUnitTest {
|
||||
|
||||
// Execute the same tests but in native mode.
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
=========
|
||||
|
||||
## A Guide to RESTEasy
|
||||
|
||||
|
||||
### Relevant Articles:
|
@ -1,4 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin)
|
||||
- [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams)
|
||||
- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy)
|
||||
|
@ -23,10 +23,6 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
|
@ -1,12 +1,8 @@
|
||||
package com.baeldung;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
@SpringBootApplication( exclude = SecurityAutoConfiguration.class)
|
||||
public class Spring5Application {
|
||||
@ -14,32 +10,4 @@ public class Spring5Application {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Spring5Application.class, args);
|
||||
}
|
||||
|
||||
public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected javax.servlet.Filter[] getServletFilters() {
|
||||
DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
|
||||
delegateFilterProxy.setTargetBeanName("loggingFilter");
|
||||
return new Filter[] { delegateFilterProxy };
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -16,14 +16,5 @@
|
||||
<servlet-name>functional</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
<filter>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
</web-app>
|
12
spring-5-reactive-2/.gitignore
vendored
Normal file
12
spring-5-reactive-2/.gitignore
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
#folders#
|
||||
.idea
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
1
spring-5-reactive-2/README.md
Normal file
1
spring-5-reactive-2/README.md
Normal file
@ -0,0 +1 @@
|
||||
## Spring 5 Reactive Project
|
50
spring-5-reactive-2/pom.xml
Normal file
50
spring-5-reactive-2/pom.xml
Normal file
@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>spring-5-reactive-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-5-reactive-2</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>spring 5 sample project about new features</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.webclient.WebClientApplication</mainClass>
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.webclient;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Tweet {
|
||||
private String text;
|
||||
private String username;
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.webclient;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class TweetsSlowServiceController {
|
||||
|
||||
@GetMapping("/slow-service-tweets")
|
||||
private List<Tweet> getAllTweets() throws Exception {
|
||||
Thread.sleep(2000L); // delay
|
||||
return Arrays.asList(
|
||||
new Tweet("RestTemplate rules", "@user1"),
|
||||
new Tweet("WebClient is better", "@user2"),
|
||||
new Tweet("OK, both are useful", "@user1"));
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.webclient;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WebClientApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebClientApplication.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package com.baeldung.webclient;
|
||||
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
public class WebController {
|
||||
|
||||
private static final int DEFAULT_PORT = 8080;
|
||||
|
||||
@Setter
|
||||
private int serverPort = DEFAULT_PORT;
|
||||
|
||||
@GetMapping("/tweets-blocking")
|
||||
public List<Tweet> getTweetsBlocking() {
|
||||
log.info("Starting BLOCKING Controller!");
|
||||
final String uri = getSlowServiceUri();
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
ResponseEntity<List<Tweet>> response = restTemplate.exchange(
|
||||
uri, HttpMethod.GET, null,
|
||||
new ParameterizedTypeReference<List<Tweet>>(){});
|
||||
|
||||
List<Tweet> result = response.getBody();
|
||||
result.forEach(tweet -> log.info(tweet.toString()));
|
||||
log.info("Exiting BLOCKING Controller!");
|
||||
return result;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<Tweet> getTweetsNonBlocking() {
|
||||
log.info("Starting NON-BLOCKING Controller!");
|
||||
Flux<Tweet> tweetFlux = WebClient.create()
|
||||
.get()
|
||||
.uri(getSlowServiceUri())
|
||||
.retrieve()
|
||||
.bodyToFlux(Tweet.class);
|
||||
|
||||
tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
|
||||
log.info("Exiting NON-BLOCKING Controller!");
|
||||
return tweetFlux;
|
||||
}
|
||||
|
||||
private String getSlowServiceUri() {
|
||||
return "http://localhost:" + serverPort + "/slow-service-tweets";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.webclient;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class)
|
||||
public class WebControllerIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
int randomServerPort;
|
||||
|
||||
@Autowired
|
||||
private WebTestClient testClient;
|
||||
|
||||
@Autowired
|
||||
private WebController webController;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
webController.setServerPort(randomServerPort);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||
testClient.get()
|
||||
.uri("/tweets-blocking")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Tweet.class)
|
||||
.hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||
testClient.get()
|
||||
.uri("/tweets-non-blocking")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Tweet.class)
|
||||
.hasSize(3);
|
||||
}
|
||||
}
|
@ -4,3 +4,4 @@
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user