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/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 93%
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-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-io/src/main/java/com/baeldung/files/Main.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java
new file mode 100644
index 0000000000..c3bcd048a4
--- /dev/null
+++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java
@@ -0,0 +1,24 @@
+package com.baeldung.files;
+
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
+
+public class Main {
+
+ private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
+
+ public static void main(String... args) throws Exception {
+ System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME));
+ System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME));
+ }
+}
diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java
new file mode 100644
index 0000000000..076825d76c
--- /dev/null
+++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java
@@ -0,0 +1,112 @@
+package com.baeldung.files;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.LineNumberReader;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileChannel.MapMode;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.util.List;
+import java.util.Scanner;
+import java.util.stream.Stream;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.LineIterator;
+
+public class NumberOfLineFinder {
+
+ public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) {
+ int lines = 0;
+ try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
+ while (reader.readLine() != null) {
+ lines++;
+ }
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) {
+ int lines = 0;
+ try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
+ reader.skip(Integer.MAX_VALUE);
+ lines = reader.getLineNumber() + 1;
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingScanner(String fileName) {
+ int lines = 0;
+ try (Scanner scanner = new Scanner(new FileReader(fileName))) {
+ while (scanner.hasNextLine()) {
+ scanner.nextLine();
+ lines++;
+ }
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) {
+ int lines = 0;
+ try (Stream fileStream = Files.lines(Paths.get(fileName))) {
+ lines = (int) fileStream.count();
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) {
+ int lines = 1;
+ try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) {
+ ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
+ while (byteBuffer.hasRemaining()) {
+ byte currentChar = byteBuffer.get();
+ if (currentChar == '\n') {
+ lines++;
+ }
+ }
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) {
+ int lines = 0;
+ try {
+ LineIterator lineIterator = FileUtils.lineIterator(new File(fileName));
+ while (lineIterator.hasNext()) {
+ lineIterator.nextLine();
+ lines++;
+ }
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+ public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) {
+ int lines = 0;
+ try {
+ List lineItems = com.google.common.io.Files.readLines(Paths.get(fileName)
+ .toFile(), Charset.defaultCharset());
+ lines = lineItems.size();
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ return lines;
+ }
+
+}
diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java
new file mode 100644
index 0000000000..6f0427ebd2
--- /dev/null
+++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.file;
+
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
+import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class NumberOfLineFinderUnitTest {
+ private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
+ private static final int ACTUAL_LINE_COUNT = 45;
+
+ @Test
+ public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingScanner_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+ @Test
+ public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() {
+ int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME);
+ assertEquals(ACTUAL_LINE_COUNT, lines);
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java
new file mode 100644
index 0000000000..6be9a18781
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java
@@ -0,0 +1,9 @@
+package com.baeldung.relationships.aggregation;
+
+import java.util.List;
+
+public class Car {
+
+ private List wheels;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java
new file mode 100644
index 0000000000..96c07f13a4
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java
@@ -0,0 +1,13 @@
+package com.baeldung.relationships.aggregation;
+
+import java.util.List;
+
+public class CarWithStaticInnerWheel {
+
+ private List wheels;
+
+ public static class Wheel {
+
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java
new file mode 100644
index 0000000000..1f38ea85ad
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java
@@ -0,0 +1,7 @@
+package com.baeldung.relationships.aggregation;
+
+public class Wheel {
+
+ private Car car;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java
new file mode 100644
index 0000000000..4c748e8084
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java
@@ -0,0 +1,7 @@
+package com.baeldung.relationships.association;
+
+public class Child {
+
+ private Mother mother;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java
new file mode 100644
index 0000000000..0e8edef125
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java
@@ -0,0 +1,9 @@
+package com.baeldung.relationships.association;
+
+import java.util.List;
+
+public class Mother {
+
+ private List children;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java
new file mode 100644
index 0000000000..1ab44f73fa
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java
@@ -0,0 +1,18 @@
+package com.baeldung.relationships.composition;
+
+import java.util.List;
+
+public class Building {
+
+ private String address;
+ private List rooms;
+
+ public class Room {
+
+ public String getBuildingAddress() {
+ return Building.this.address;
+ }
+
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java
new file mode 100644
index 0000000000..4e3411cf30
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java
@@ -0,0 +1,28 @@
+package com.baeldung.relationships.composition;
+
+public class BuildingWithDefinitionRoomInMethod {
+
+ public Room createAnonymousRoom() {
+ return new Room() {
+ @Override
+ public void doInRoom() {}
+ };
+ }
+
+ public Room createInlineRoom() {
+ class InlineRoom implements Room {
+ @Override
+ public void doInRoom() {}
+ }
+ return new InlineRoom();
+ }
+
+ public Room createLambdaRoom() {
+ return () -> {};
+ }
+
+ public interface Room {
+ void doInRoom();
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java
new file mode 100644
index 0000000000..63cfd1b89e
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java
@@ -0,0 +1,9 @@
+package com.baeldung.relationships.university;
+
+import java.util.List;
+
+public class Department {
+
+ private List professors;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java
new file mode 100644
index 0000000000..8e1258c3e6
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java
@@ -0,0 +1,10 @@
+package com.baeldung.relationships.university;
+
+import java.util.List;
+
+public class Professor {
+
+ private List department;
+ private List friends;
+
+}
diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java
new file mode 100644
index 0000000000..e5e518e0f1
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java
@@ -0,0 +1,9 @@
+package com.baeldung.relationships.university;
+
+import java.util.List;
+
+public class University {
+
+ private List department;
+
+}
diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java
new file mode 100644
index 0000000000..d73f2a2708
--- /dev/null
+++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java
@@ -0,0 +1,29 @@
+package com.baeldung.sasl;
+
+import java.io.IOException;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.sasl.RealmCallback;
+
+public class ClientCallbackHandler implements CallbackHandler {
+
+ @Override
+ public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
+ for (Callback cb : cbs) {
+ if (cb instanceof NameCallback) {
+ NameCallback nc = (NameCallback) cb;
+ nc.setName("username");
+ } else if (cb instanceof PasswordCallback) {
+ PasswordCallback pc = (PasswordCallback) cb;
+ pc.setPassword("password".toCharArray());
+ } else if (cb instanceof RealmCallback) {
+ RealmCallback rc = (RealmCallback) cb;
+ rc.setText("myServer");
+ }
+ }
+ }
+}
diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java
new file mode 100644
index 0000000000..3e071d68cc
--- /dev/null
+++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java
@@ -0,0 +1,34 @@
+package com.baeldung.sasl;
+
+import java.io.IOException;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.sasl.AuthorizeCallback;
+import javax.security.sasl.RealmCallback;
+
+public class ServerCallbackHandler implements CallbackHandler {
+
+ @Override
+ public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
+ for (Callback cb : cbs) {
+ if (cb instanceof AuthorizeCallback) {
+ AuthorizeCallback ac = (AuthorizeCallback) cb;
+ ac.setAuthorized(true);
+ } else if (cb instanceof NameCallback) {
+ NameCallback nc = (NameCallback) cb;
+ nc.setName("username");
+
+ } else if (cb instanceof PasswordCallback) {
+ PasswordCallback pc = (PasswordCallback) cb;
+ pc.setPassword("password".toCharArray());
+ } else if (cb instanceof RealmCallback) {
+ RealmCallback rc = (RealmCallback) cb;
+ rc.setText("myServer");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java
new file mode 100644
index 0000000000..6601654781
--- /dev/null
+++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java
@@ -0,0 +1,76 @@
+package com.baeldung.sasl;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.sasl.Sasl;
+import javax.security.sasl.SaslClient;
+import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class SaslUnitTest {
+
+ private static final String MECHANISM = "DIGEST-MD5";
+ private static final String SERVER_NAME = "myServer";
+ private static final String PROTOCOL = "myProtocol";
+ private static final String AUTHORIZATION_ID = null;
+ private static final String QOP_LEVEL = "auth-conf";
+
+ private SaslServer saslServer;
+ private SaslClient saslClient;
+
+ @Before
+ public void setUp() throws SaslException {
+
+ ServerCallbackHandler serverHandler = new ServerCallbackHandler();
+ ClientCallbackHandler clientHandler = new ClientCallbackHandler();
+
+ Map props = new HashMap<>();
+ props.put(Sasl.QOP, QOP_LEVEL);
+
+ saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler);
+ saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler);
+
+ }
+
+ @Test
+ public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {
+
+ byte[] challenge;
+ byte[] response;
+
+ challenge = saslServer.evaluateResponse(new byte[0]);
+ response = saslClient.evaluateChallenge(challenge);
+
+ challenge = saslServer.evaluateResponse(response);
+ response = saslClient.evaluateChallenge(challenge);
+
+ assertTrue(saslServer.isComplete());
+ assertTrue(saslClient.isComplete());
+
+ String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
+ assertEquals("auth-conf", qop);
+
+ byte[] outgoing = "Baeldung".getBytes();
+ byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);
+
+ byte[] secureIncoming = secureOutgoing;
+ byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
+ assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
+ }
+
+ @After
+ public void tearDown() throws SaslException {
+ saslClient.dispose();
+ saslServer.dispose();
+ }
+
+}
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/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-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java
new file mode 100644
index 0000000000..effdee07ad
--- /dev/null
+++ b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java
@@ -0,0 +1,148 @@
+package com.baeldung.binarynumbers;
+
+public class BinaryNumbers {
+
+ /**
+ * This method takes a decimal number and convert it into a binary number.
+ * example:- input:10, output:1010
+ *
+ * @param decimalNumber
+ * @return binary number
+ */
+ public Integer convertDecimalToBinary(Integer decimalNumber) {
+
+ if (decimalNumber == 0) {
+ return decimalNumber;
+ }
+
+ StringBuilder binaryNumber = new StringBuilder();
+
+ while (decimalNumber > 0) {
+
+ int remainder = decimalNumber % 2;
+ int result = decimalNumber / 2;
+
+ binaryNumber.append(remainder);
+ decimalNumber = result;
+ }
+
+ binaryNumber = binaryNumber.reverse();
+
+ return Integer.valueOf(binaryNumber.toString());
+ }
+
+ /**
+ * This method takes a binary number and convert it into a decimal number.
+ * example:- input:101, output:5
+ *
+ * @param binary number
+ * @return decimal Number
+ */
+ public Integer convertBinaryToDecimal(Integer binaryNumber) {
+
+ Integer result = 0;
+ Integer base = 1;
+
+ while (binaryNumber > 0) {
+
+ int lastDigit = binaryNumber % 10;
+ binaryNumber = binaryNumber / 10;
+
+ result += lastDigit * base;
+
+ base = base * 2;
+ }
+ return result;
+ }
+
+ /**
+ * This method accepts two binary numbers and returns sum of input numbers.
+ * Example:- firstNum: 101, secondNum: 100, output: 1001
+ *
+ * @param firstNum
+ * @param secondNum
+ * @return addition of input numbers
+ */
+ public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
+
+ StringBuilder output = new StringBuilder();
+
+ int carry = 0;
+ int temp;
+
+ while (firstNum != 0 || secondNum != 0) {
+
+ temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
+ output.append(temp);
+
+ carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
+
+ firstNum = firstNum / 10;
+ secondNum = secondNum / 10;
+ }
+
+ if (carry != 0) {
+ output.append(carry);
+ }
+
+ return Integer.valueOf(output.reverse()
+ .toString());
+ }
+
+ /**
+ * This method takes two binary number as input and subtract second number from the first number.
+ * example:- firstNum: 1000, secondNum: 11, output: 101
+ * @param firstNum
+ * @param secondNum
+ * @return Result of subtraction of secondNum from first
+ */
+ public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
+
+ int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
+
+ StringBuilder output = new StringBuilder();
+
+ int carry = 0;
+ int temp;
+
+ while (firstNum != 0 || onesComplement != 0) {
+
+ temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
+ output.append(temp);
+
+ carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
+
+ firstNum = firstNum / 10;
+ onesComplement = onesComplement / 10;
+ }
+
+ String additionOfFirstNumAndOnesComplement = output.reverse()
+ .toString();
+
+ if (carry == 1) {
+ return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
+ } else {
+ return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
+ }
+
+ }
+
+ public Integer getOnesComplement(Integer num) {
+
+ StringBuilder onesComplement = new StringBuilder();
+
+ while (num > 0) {
+ int lastDigit = num % 10;
+ if (lastDigit == 0) {
+ onesComplement.append(1);
+ } else {
+ onesComplement.append(0);
+ }
+ num = num / 10;
+ }
+
+ return Integer.valueOf(onesComplement.reverse()
+ .toString());
+ }
+
+}
diff --git a/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java
new file mode 100644
index 0000000000..ca6022261d
--- /dev/null
+++ b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.binarynumbers;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class BinaryNumbersUnitTest {
+
+ private BinaryNumbers binaryNumbers = new BinaryNumbers();
+
+ @Test
+ public void given_decimalNumber_then_returnBinaryNumber() {
+ assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
+ assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
+ }
+
+ @Test
+ public void given_decimalNumber_then_convertToBinaryNumber() {
+ assertEquals("1000", Integer.toBinaryString(8));
+ assertEquals("10100", Integer.toBinaryString(20));
+ }
+
+ @Test
+ public void given_binaryNumber_then_ConvertToDecimalNumber() {
+ assertEquals(8, Integer.parseInt("1000", 2));
+ assertEquals(20, Integer.parseInt("10100", 2));
+ }
+
+ @Test
+ public void given_binaryNumber_then_returnDecimalNumber() {
+ assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
+ assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
+ }
+
+ @Test
+ public void given_twoBinaryNumber_then_returnAddition() {
+ // adding 4 and 10
+ assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
+
+ // adding 26 and 14
+ assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
+ }
+
+ @Test
+ public void given_twoBinaryNumber_then_returnSubtraction() {
+ // subtracting 16 from 25
+ assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
+
+ // subtracting 29 from 16, the output here is negative
+ assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
+ }
+
+ @Test
+ public void given_binaryLiteral_thenReturnDecimalValue() {
+
+ byte five = 0b101;
+ assertEquals((byte) 5, five);
+
+ short three = 0b11;
+ assertEquals((short) 3, three);
+
+ int nine = 0B1001;
+ assertEquals(9, nine);
+
+ long twentyNine = 0B11101;
+ assertEquals(29, twentyNine);
+
+ int minusThirtySeven = -0B100101;
+ assertEquals(-37, minusThirtySeven);
+
+ }
+
+}
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/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java
new file mode 100644
index 0000000000..9abb7ac453
--- /dev/null
+++ b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.string.todouble;
+
+import static org.junit.Assert.assertEquals;
+
+import java.text.DecimalFormat;
+import java.text.ParseException;
+
+import org.junit.Test;
+
+public class StringToDoubleConversionUnitTest {
+
+ @Test
+ public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() {
+ assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() {
+ Double.parseDouble(null);
+ }
+
+ @Test(expected = NumberFormatException.class)
+ public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() {
+ Double.parseDouble("&");
+ }
+
+ @Test
+ public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() {
+ assertEquals(1.23, Double.valueOf("1.23"), 0.000001);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() {
+ Double.valueOf(null);
+ }
+
+ @Test(expected = NumberFormatException.class)
+ public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() {
+ Double.valueOf("&");
+ }
+
+ @Test
+ public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException {
+ assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException {
+ new DecimalFormat("#").parse(null);
+ }
+
+ @Test(expected = ParseException.class)
+ public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException {
+ new DecimalFormat("#").parse("&");
+ }
+}
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")}
+
+
+