diff --git a/README.md b/README.md
index 7f78cf1515..4cad075cc3 100644
--- a/README.md
+++ b/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):
-**[>> 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:
-**[>> 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:
+**[>> 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):
+**[>> 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":
+**[>> 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`
diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java
new file mode 100644
index 0000000000..376b196aa1
--- /dev/null
+++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java
@@ -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 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;
+ }
+ }
+
+}
diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java
new file mode 100644
index 0000000000..549151bc93
--- /dev/null
+++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java
@@ -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 testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
+
+ testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
+
+ List expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
+
+ assertEquals(expected, testStrings);
+
+
+ }
+
+ @Test
+ public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
+
+ List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
+
+ testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
+
+ List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
+
+ assertEquals(expected, testStrings);
+
+
+ }
+
+ @Test
+ public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
+
+ List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
+
+ testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
+
+ List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
+
+ assertEquals(expected, testStrings);
+
+
+ }
+
+ @Test
+ public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
+
+ List testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
+
+ List expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
+
+ testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
+
+ assertEquals(expected, testStrings);
+
+ }
+
+ @Test
+ public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
+
+ List testStrings = Arrays.asList("a", "c", "d", "e");
+ List expected = new ArrayList<>(testStrings);
+
+ testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
+
+ assertEquals(expected, testStrings);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md
index 4514fd1a2b..6c603e4dea 100644
--- a/core-java-modules/core-java-12/README.md
+++ b/core-java-modules/core-java-12/README.md
@@ -1,3 +1,4 @@
-## Relevant articles:
+## Relevant Articles:
+
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
diff --git a/core-java-modules/core-java-arrays-2/.gitignore b/core-java-modules/core-java-arrays-2/.gitignore
new file mode 100644
index 0000000000..374c8bf907
--- /dev/null
+++ b/core-java-modules/core-java-arrays-2/.gitignore
@@ -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
\ No newline at end of file
diff --git a/core-java-arrays/README.MD b/core-java-modules/core-java-arrays-2/README.MD
similarity index 100%
rename from core-java-arrays/README.MD
rename to core-java-modules/core-java-arrays-2/README.MD
diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml
new file mode 100644
index 0000000000..bfe8a349e1
--- /dev/null
+++ b/core-java-modules/core-java-arrays-2/pom.xml
@@ -0,0 +1,50 @@
+
+ 4.0.0
+ com.baeldung
+ core-java-arrays-2
+ 0.1.0-SNAPSHOT
+ core-java-arrays-2
+ jar
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj-core.version}
+ test
+
+
+
+
+ core-java-arrays-2
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+
+ 3.9
+
+ 3.10.0
+
+
+
diff --git a/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java
similarity index 100%
rename from core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java
rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java
diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java
similarity index 100%
rename from core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java
rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java
diff --git a/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java
similarity index 100%
rename from core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java
rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java
diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java
similarity index 92%
rename from core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java
rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java
index df6079270b..5f670f4a59 100644
--- a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java
+++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java
@@ -4,7 +4,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
-public class LoopDiagonallyTest {
+public class LoopDiagonallyUnitTest {
@Test
public void twoArrayIsLoopedDiagonallyAsExpected() {
diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java
index ec612fd53b..78a9a8f4d1 100644
--- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java
+++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java
@@ -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);
}
}
diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java
index 29866a3c22..7971e0eab7 100644
--- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java
+++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java
@@ -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);
}
+
}
\ No newline at end of file
diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md
index 5338789a2f..79e5bad23a 100644
--- a/core-java-modules/core-java-exceptions/README.md
+++ b/core-java-modules/core-java-exceptions/README.md
@@ -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)
diff --git a/core-java-modules/core-java-networking-2/.gitignore b/core-java-modules/core-java-networking-2/.gitignore
new file mode 100644
index 0000000000..374c8bf907
--- /dev/null
+++ b/core-java-modules/core-java-networking-2/.gitignore
@@ -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
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml
new file mode 100644
index 0000000000..8a26f6ab9f
--- /dev/null
+++ b/core-java-modules/core-java-networking-2/pom.xml
@@ -0,0 +1,20 @@
+
+ 4.0.0
+ core-java-networking-2
+ core-java-networking-2
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+
+ core-java-networking-2
+
+
diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java
new file mode 100644
index 0000000000..b99e74f8bf
--- /dev/null
+++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java
@@ -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();
+ }
+
+}
diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java
new file mode 100644
index 0000000000..5e295e65a0
--- /dev/null
+++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java
@@ -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);
+ }
+
+}
diff --git a/core-java-modules/multimodulemavenproject/README.md b/core-java-modules/multimodulemavenproject/README.md
new file mode 100644
index 0000000000..fc4ca60b6b
--- /dev/null
+++ b/core-java-modules/multimodulemavenproject/README.md
@@ -0,0 +1,3 @@
+## Relevant Articles
+
+- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index 11a1003460..2dca62005d 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -17,6 +17,7 @@
pre-jpms
core-java-exceptions
core-java-optional
+ core-java-networking-2
diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java
new file mode 100644
index 0000000000..16b7e04297
--- /dev/null
+++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java
@@ -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> adjVertices;
+
+ public Graph() {
+ this.adjVertices = new HashMap>();
+ }
+
+ 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 stack = new Stack();
+ 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 result = new Stack();
+ 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 result) {
+ isVisited[current] = true;
+ for (int dest : adjVertices.get(current)) {
+ if (!isVisited[dest])
+ topologicalSortRecursive(dest, isVisited, result);
+ }
+ result.push(current);
+ }
+
+}
diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
index f435e41afa..ff73ee8e54 100644
--- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
+++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
@@ -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 stack = new Stack();
+ 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 stack = new Stack();
+ 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 stack = new Stack();
+ 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;
diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java
new file mode 100644
index 0000000000..249cb6e093
--- /dev/null
+++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java
@@ -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;
+ }
+}
diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
index f81247b74d..f99cb52ed7 100644
--- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
+++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
@@ -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
diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java
new file mode 100644
index 0000000000..c395b61068
--- /dev/null
+++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java
@@ -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));
+ }
+}
diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java
new file mode 100644
index 0000000000..1807f854b2
--- /dev/null
+++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java
@@ -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));
+ }
+}
diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java
new file mode 100644
index 0000000000..6df1b79a60
--- /dev/null
+++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java
@@ -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;
+ }
+}
diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java
new file mode 100644
index 0000000000..525dd7d1ad
--- /dev/null
+++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java
@@ -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> 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> 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> 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> 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> violations = validator.validate(invoice);
+ assertThat(violations.size()).isEqualTo(0);
+ }
+
+}
diff --git a/JGit/README.md b/jgit/README.md
similarity index 100%
rename from JGit/README.md
rename to jgit/README.md
diff --git a/JGit/pom.xml b/jgit/pom.xml
similarity index 100%
rename from JGit/pom.xml
rename to jgit/pom.xml
diff --git a/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java
rename to jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/OpenRepository.java
rename to jgit/src/main/java/com/baeldung/jgit/OpenRepository.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/helper/Helper.java
rename to jgit/src/main/java/com/baeldung/jgit/helper/Helper.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java
rename to jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java
rename to jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java
rename to jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java
similarity index 100%
rename from JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
rename to jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java
diff --git a/JGit/src/main/resources/logback.xml b/jgit/src/main/resources/logback.xml
similarity index 100%
rename from JGit/src/main/resources/logback.xml
rename to jgit/src/main/resources/logback.xml
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
similarity index 100%
rename from JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
rename to jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
similarity index 100%
rename from JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
rename to jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
diff --git a/jhipster/jhipster-microservice/README.md b/jhipster/jhipster-microservice/README.md
new file mode 100644
index 0000000000..7abe3204c4
--- /dev/null
+++ b/jhipster/jhipster-microservice/README.md
@@ -0,0 +1,3 @@
+## Relevant Articles
+
+- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices)
diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md
index a2c267b74d..65cc51ad88 100644
--- a/jhipster/jhipster-monolithic/README.md
+++ b/jhipster/jhipster-monolithic/README.md
@@ -1,4 +1,6 @@
-### Relevant articles
+## Relevant Articles
+
+- [Intro to JHipster](https://www.baeldung.com/jhipster)
# baeldung
diff --git a/jhipster/jhipster-uaa/README.md b/jhipster/jhipster-uaa/README.md
new file mode 100644
index 0000000000..3971e3c8c6
--- /dev/null
+++ b/jhipster/jhipster-uaa/README.md
@@ -0,0 +1,3 @@
+## Relevant Articles
+
+- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java
index 10e78a2dfd..ba5e1ec359 100644
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java
@@ -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.")
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java
index f39bb2ea2d..0ea12da16e 100644
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java
@@ -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 supportedGrantTypes = Collections.singletonList("authorization_code");
+ List 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();
}
}
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java
new file mode 100644
index 0000000000..324bacb33f
--- /dev/null
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java
@@ -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();
+ }
+}
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java
index 889c7fcea2..78128aead6 100644
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java
@@ -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 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();
}
}
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java
new file mode 100644
index 0000000000..63e3552353
--- /dev/null
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java
@@ -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 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 rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
+ Set 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();
+ }
+}
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp
index 1004b5b8b7..41b0582c03 100644
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp
+++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp
@@ -41,8 +41,8 @@
-
-
+
+
|
diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java
new file mode 100644
index 0000000000..7059c4f7e1
--- /dev/null
+++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java
@@ -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;
+ }
+}
diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java
index 87aa8bc668..e72877076c 100644
--- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java
+++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java
@@ -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;
- }
}
diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java
new file mode 100644
index 0000000000..a519a53070
--- /dev/null
+++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java
@@ -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);
+ }
+}
diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp
index 23fec70f33..ccb74df228 100644
--- a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp
+++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp
@@ -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 @@
access_token: ${tokenResponse.getString("access_token")}
scope: ${tokenResponse.getString("scope")}
Expires in (s): ${tokenResponse.getInt("expires_in")}
+ refresh_token: ${tokenResponse.getString("refresh_token")}
+
+
+