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/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java
new file mode 100644
index 0000000000..c130e2d866
--- /dev/null
+++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java
@@ -0,0 +1,20 @@
+package com.baeldung.algorithms.shellsort;
+
+public class ShellSort {
+
+ public static void sort(int arrayToSort[]) {
+ int n = arrayToSort.length;
+
+ for (int gap = n / 2; gap > 0; gap /= 2) {
+ for (int i = gap; i < n; i++) {
+ int key = arrayToSort[i];
+ int j = i;
+ while (j >= gap && arrayToSort[j - gap] > key) {
+ arrayToSort[j] = arrayToSort[j - gap];
+ j -= gap;
+ }
+ arrayToSort[j] = key;
+ }
+ }
+ }
+}
diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java
new file mode 100644
index 0000000000..91a27c41d0
--- /dev/null
+++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.algorithms.shellsort;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertArrayEquals;
+
+import org.junit.Test;
+
+public class ShellSortUnitTest {
+
+ @Test
+ public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
+ int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
+ ShellSort.sort(input);
+ int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
+ assertArrayEquals("the two arrays are not equal", expected, input);
+ }
+}
diff --git a/axon/pom.xml b/axon/pom.xml
index 2b9ac1fcdd..3d30cceb83 100644
--- a/axon/pom.xml
+++ b/axon/pom.xml
@@ -18,12 +18,6 @@
org.axonframework
axon-spring-boot-starter
${axon.version}
-
-
- org.axonframework
- axon-server-connector
-
-
@@ -58,7 +52,7 @@
- 4.0.3
+ 4.1.2
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java
index b37b2fdd66..4ef02e6b54 100644
--- a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java
+++ b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java
@@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
+import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
@Aggregate
public class OrderAggregate {
@@ -34,7 +35,7 @@ public class OrderAggregate {
@CommandHandler
public void handle(ShipOrderCommand command) {
if (!orderConfirmed) {
- throw new IllegalStateException("Cannot ship an order which has not been confirmed yet.");
+ throw new UnconfirmedOrderException();
}
apply(new OrderShippedEvent(orderId));
@@ -43,12 +44,12 @@ public class OrderAggregate {
@EventSourcingHandler
public void on(OrderPlacedEvent event) {
this.orderId = event.getOrderId();
- orderConfirmed = false;
+ this.orderConfirmed = false;
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
- orderConfirmed = true;
+ this.orderConfirmed = true;
}
protected OrderAggregate() {
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java
new file mode 100644
index 0000000000..1873bc6893
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java
@@ -0,0 +1,8 @@
+package com.baeldung.axon.coreapi.exceptions;
+
+public class UnconfirmedOrderException extends IllegalStateException {
+
+ public UnconfirmedOrderException() {
+ super("Cannot ship an order which has not been confirmed yet.");
+ }
+}
diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java
index d4cf3d999b..a37f0111ed 100644
--- a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java
+++ b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java
@@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Service;
@@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
import com.baeldung.axon.coreapi.queries.OrderedProduct;
@Service
+@ProcessingGroup("ordered-products")
public class OrderedProductsEventHandler {
private final Map orderedProducts = new HashMap<>();
diff --git a/axon/src/main/resources/application.properties b/axon/src/main/resources/application.properties
new file mode 100644
index 0000000000..7c51eb8e1e
--- /dev/null
+++ b/axon/src/main/resources/application.properties
@@ -0,0 +1 @@
+spring.application.name=Order Management Service
\ No newline at end of file
diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java
index 9beedbaa19..aaefe49fb1 100644
--- a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java
+++ b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java
@@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel;
import java.util.UUID;
+import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.*;
@@ -41,12 +42,12 @@ public class OrderAggregateUnitTest {
}
@Test
- public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() {
+ public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
String orderId = UUID.randomUUID().toString();
String product = "Deluxe Chair";
fixture.given(new OrderPlacedEvent(orderId, product))
.when(new ShipOrderCommand(orderId))
- .expectException(IllegalStateException.class);
+ .expectException(UnconfirmedOrderException.class);
}
@Test
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-modules/core-java-arrays-2/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
new file mode 100644
index 0000000000..71e2840f45
--- /dev/null
+++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java
@@ -0,0 +1,45 @@
+package com.baeldung.array.looping;
+
+public class LoopDiagonally {
+
+
+ public String loopDiagonally(String[][] twoDArray) {
+
+ int length = twoDArray.length;
+ int diagonalLines = (length + length) - 1;
+ int itemsInDiagonal = 0;
+ int midPoint = (diagonalLines / 2) + 1;
+ StringBuilder output = new StringBuilder();
+
+ for (int i = 1; i <= diagonalLines; i++) {
+
+ StringBuilder items = new StringBuilder();
+ int rowIndex;
+ int columnIndex;
+
+ if (i <= midPoint) {
+ itemsInDiagonal++;
+ for (int j = 0; j < itemsInDiagonal; j++) {
+ rowIndex = (i - j) - 1;
+ columnIndex = j;
+ items.append(twoDArray[rowIndex][columnIndex]);
+ }
+ } else {
+ itemsInDiagonal--;
+ for (int j = 0; j < itemsInDiagonal; j++) {
+ rowIndex = (length - 1) - j;
+ columnIndex = (i - length) + j;
+ items.append(twoDArray[rowIndex][columnIndex]);
+ }
+ }
+
+ if (i != diagonalLines) {
+ output.append(items).append(" ");
+ } else {
+ output.append(items);
+ }
+ }
+
+ return output.toString();
+ }
+}
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-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java
new file mode 100644
index 0000000000..5f670f4a59
--- /dev/null
+++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.array.looping;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class LoopDiagonallyUnitTest {
+
+ @Test
+ public void twoArrayIsLoopedDiagonallyAsExpected() {
+
+ LoopDiagonally loopDiagonally = new LoopDiagonally();
+ String[][] twoDArray = {{"a", "b", "c"},
+ {"d", "e", "f"},
+ {"g", "h", "i"}};
+
+ String output = loopDiagonally.loopDiagonally(twoDArray);
+ assertEquals("a db gec hf i", output);
+ }
+}
\ No newline at end of file
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-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-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java
new file mode 100644
index 0000000000..ee17c1e8ea
--- /dev/null
+++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.incrementdecrementunaryoperator;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class IncrementDecrementUnaryOperatorUnitTest {
+
+ @Test
+ public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
+ int operand = 1;
+ ++operand;
+ assertThat(operand).isEqualTo(2);
+ }
+
+ @Test
+ public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() {
+ int operand = 1;
+ int number = ++operand;
+ assertThat(number).isEqualTo(2);
+ }
+
+ @Test
+ public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
+ int operand = 1;
+ --operand;
+ assertThat(operand).isEqualTo(0);
+ }
+
+ @Test
+ public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() {
+ int operand = 1;
+ int number = --operand;
+ assertThat(number).isEqualTo(0);
+ }
+
+ @Test
+ public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
+ int operand = 1;
+ operand++;
+ assertThat(operand).isEqualTo(2);
+ }
+
+ @Test
+ public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
+ int operand = 1;
+ int number = operand++;
+ assertThat(number).isEqualTo(1);
+ }
+
+ @Test
+ public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
+ int operand = 1;
+ operand--;
+ assertThat(operand).isEqualTo(0);
+ }
+
+ @Test
+ public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
+ int operand = 1;
+ int number = operand--;
+ assertThat(number).isEqualTo(1);
+ }
+}
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/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/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-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/README.MD b/java-strings-2/README.MD
index c6d4f0222a..b4b16fbaef 100644
--- a/java-strings-2/README.MD
+++ b/java-strings-2/README.MD
@@ -3,5 +3,20 @@
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
+- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
+- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
+- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
+- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
+- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
+- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
+- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
+- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
+- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
+- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
+- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
+- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
+- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
+- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
+- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)
diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml
index 7342953d15..be47b1ec89 100755
--- a/java-strings-2/pom.xml
+++ b/java-strings-2/pom.xml
@@ -40,6 +40,16 @@
commons-lang3
${commons-lang3.version}
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
junit
junit
@@ -52,32 +62,54 @@
${org.hamcrest.version}
test
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+
+ org.passay
+ passay
+ ${passay.version}
+
org.apache.commons
commons-text
${commons-text.version}
+
+ com.vdurmont
+ emoji-java
+ ${emoji-java.version}
+
+
+ org.ahocorasick
+ ahocorasick
+ ${ahocorasick.version}
+
javax.validation
validation-api
- 2.0.0.Final
+ ${validation-api.version}
org.hibernate.validator
hibernate-validator
- 6.0.2.Final
+ ${hibernate-validator.version}
javax.el
javax.el-api
- 3.0.0
+ ${javax.el-api.version}
org.glassfish.web
javax.el
- 2.2.6
+ ${javax.el.version}
-
@@ -105,9 +137,19 @@
3.8.1
+ 1.10
+ 1.3.1
+
+ 3.6.1
+ 4.0.0
+ 0.4.0
61.1
28.0-jre
1.4
+ 2.0.0.Final
+ 6.0.2.Final
+ 3.0.0
+ 2.2.6
\ No newline at end of file
diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/MatchWords.java
rename to java-strings-2/src/main/java/com/baeldung/string/MatchWords.java
diff --git a/java-strings/src/main/java/com/baeldung/string/Pangram.java b/java-strings-2/src/main/java/com/baeldung/string/Pangram.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/Pangram.java
rename to java-strings-2/src/main/java/com/baeldung/string/Pangram.java
diff --git a/java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java b/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java
rename to java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java
diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java
rename to java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java
diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java
rename to java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java
diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java
rename to java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java
diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java
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/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java
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/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java
rename to java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java
diff --git a/java-strings/src/test/resources/test_image.jpg b/java-strings-2/src/test/resources/test_image.jpg
similarity index 100%
rename from java-strings/src/test/resources/test_image.jpg
rename to java-strings-2/src/test/resources/test_image.jpg
diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md
new file mode 100644
index 0000000000..d909f171a7
--- /dev/null
+++ b/java-strings-ops/README.md
@@ -0,0 +1,22 @@
+=========
+
+## Java Strings Cookbooks and Examples
+
+### Relevant Articles:
+- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
+- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
+- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
+- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
+- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
+- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
+- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
+- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
+- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
+- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
+- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
+- [Split a String in Java](http://www.baeldung.com/java-split-string)
+- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
+- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
+- [Java toString() Method](https://www.baeldung.com/java-tostring)
+- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
+- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
\ No newline at end of file
diff --git a/java-strings-ops/pom.xml b/java-strings-ops/pom.xml
new file mode 100644
index 0000000000..b6a7ea2728
--- /dev/null
+++ b/java-strings-ops/pom.xml
@@ -0,0 +1,99 @@
+
+ 4.0.0
+ com.baeldung
+ java-strings-ops
+ 0.1.0-SNAPSHOT
+ jar
+ java-strings-ops
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.openjdk.jmh
+ jmh-core
+ ${jmh-core.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${jmh-generator.version}
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit-jupiter-api.version}
+ test
+
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
+
+
+
+
+ java-strings-ops
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${java.version}
+ -parameters
+
+
+
+
+
+
+
+ 3.8.1
+
+ 3.6.1
+ 27.0.1-jre
+ 5.3.1
+
+
+
diff --git a/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
rename to java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
diff --git a/java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
rename to java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
diff --git a/java-strings/src/main/java/com/baeldung/string/Palindrome.java b/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/Palindrome.java
rename to java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java
diff --git a/java-strings/src/main/java/com/baeldung/string/StringHelper.java b/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/StringHelper.java
rename to java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/Customer.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java
diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/tostring/Order.java
rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java
diff --git a/JGit/src/main/resources/logback.xml b/java-strings-ops/src/main/resources/logback.xml
similarity index 100%
rename from JGit/src/main/resources/logback.xml
rename to java-strings-ops/src/main/resources/logback.xml
diff --git a/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/README.md b/java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java/conversion/README.md
rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md
diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java
diff --git a/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java
similarity index 100%
rename from java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java
rename to java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java
diff --git a/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java
diff --git a/java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java
similarity index 100%
rename from java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java
rename to java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java
diff --git a/spring-security-mvc-session/.gitignore b/java-strings-ops/src/test/resources/.gitignore
similarity index 100%
rename from spring-security-mvc-session/.gitignore
rename to java-strings-ops/src/test/resources/.gitignore
diff --git a/java-strings/README.md b/java-strings/README.md
index b342f53918..ef536b4099 100644
--- a/java-strings/README.md
+++ b/java-strings/README.md
@@ -6,51 +6,18 @@
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
-- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
-- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
-- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
-- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
-- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
-- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
-- [Split a String in Java](http://www.baeldung.com/java-split-string)
-- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
-- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
-- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
-- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
-- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
-- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
-- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
-- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
-- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
-- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
-- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
-- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
-- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
-- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
-- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
-- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
-- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
-- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
-- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
-- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
-- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
-- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
-- [Java toString() Method](https://www.baeldung.com/java-tostring)
-- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
-- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
-- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
-- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
+- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
\ No newline at end of file
diff --git a/java-strings/pom.xml b/java-strings/pom.xml
index 7f66b95355..42a57bfb42 100755
--- a/java-strings/pom.xml
+++ b/java-strings/pom.xml
@@ -62,12 +62,6 @@
guava
${guava.version}
-
-
- com.vdurmont
- emoji-java
- ${emoji-java.version}
-
org.junit.jupiter
@@ -83,24 +77,6 @@
test
-
-
- org.passay
- passay
- ${passay.version}
-
-
- org.apache.commons
- commons-text
- ${commons-text.version}
-
-
-
- org.ahocorasick
- ahocorasick
- ${ahocorasick.version}
-
-
@@ -134,11 +110,8 @@
3.6.1
61.1
27.0.1-jre
- 4.0.0
5.3.1
- 1.3.1
1.4
- 0.4.0
diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java
new file mode 100644
index 0000000000..b4d80db0ab
--- /dev/null
+++ b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java
@@ -0,0 +1,57 @@
+package com.baeldung.servlets;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping")
+public class MyHttpServlet extends HttpServlet {
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ PrintWriter writer = response.getWriter();
+ writer.println(request.getParameter("function"));
+ if ("getContextPath".equals(request.getParameter("function"))) {
+ writer.println(request.getContextPath());
+ } else if ("getLocalAddr".equals(request.getParameter("function"))) {
+ writer.println(request.getLocalAddr());
+ } else if ("getLocalName".equals(request.getParameter("function"))) {
+ writer.println(request.getLocalName());
+ } else if ("getLocalAPort".equals(request.getParameter("function"))) {
+ writer.println(request.getLocalPort());
+ } else if ("getMethod".equals(request.getParameter("function"))) {
+ writer.println(request.getMethod());
+ } else if ("getParameterNames".equals(request.getParameter("function"))) {
+ writer.println(request.getParameterNames());
+ } else if ("getPathInfo".equals(request.getParameter("function"))) {
+ writer.println(request.getPathInfo());
+ } else if ("getProtocol".equals(request.getParameter("function"))) {
+ writer.println(request.getProtocol());
+ } else if ("getQueryString".equals(request.getParameter("function"))) {
+ writer.println(request.getQueryString());
+ } else if ("getRequestedSessionId".equals(request.getParameter("function"))) {
+ writer.println(request.getRequestedSessionId());
+ } else if ("getRequestURI".equals(request.getParameter("function"))) {
+ writer.println(request.getRequestURI());
+ } else if ("getRequestURL".equals(request.getParameter("function"))) {
+ writer.println(request.getRequestURL());
+ } else if ("getScheme".equals(request.getParameter("function"))) {
+ writer.println(request.getScheme());
+ } else if ("getServerName".equals(request.getParameter("function"))) {
+ writer.println(request.getServerName());
+ } else if ("getServerPort".equals(request.getParameter("function"))) {
+ writer.println(request.getServerPort());
+ } else if ("getServletPath".equals(request.getParameter("function"))) {
+ writer.println(request.getServletPath());
+ } else {
+ writer.println("INVALID FUNCTION");
+ }
+ writer.flush();
+ }
+
+}
+
+
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/Twitter4J/src/main/resources/logback.xml b/jgit/src/main/resources/logback.xml
similarity index 100%
rename from Twitter4J/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/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java
deleted file mode 100644
index 84b9a89c54..0000000000
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java
+++ /dev/null
@@ -1,209 +0,0 @@
-//package com.baeldung.security.oauth2.server.web;
-//
-//import AuthorizationCode;
-//import Client;
-//import User;
-//import com.baeldung.security.oauth2.server.service.AuthCodeService;
-//
-//import javax.ejb.EJB;
-//import javax.enterprise.context.RequestScoped;
-//import javax.inject.Inject;
-//import javax.persistence.EntityManager;
-//import javax.persistence.PersistenceContext;
-//import javax.security.enterprise.SecurityContext;
-//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
-//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
-//import javax.servlet.ServletException;
-//import javax.servlet.annotation.HttpConstraint;
-//import javax.servlet.annotation.ServletSecurity;
-//import javax.servlet.annotation.WebServlet;
-//import javax.servlet.http.HttpServlet;
-//import javax.servlet.http.HttpServletRequest;
-//import javax.servlet.http.HttpServletResponse;
-//import java.io.IOException;
-//import java.security.Principal;
-//import java.util.*;
-//
-///**
-// * 1. GET http://localhost:8080/app/ (302)
-// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302)
-// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input
-// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302)
-// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200)
-// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302)
-// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200)
-// */
-///*
-//
-//Query Params:
-// client_id: app
-// redirect_uri: http://localhost:8080/app/
-// response_type: code
-// state: A123
-//
-// ==> GET user login WITH client request as hidden input:
-//
-//
-// ==> After user login ==> Initial client request
-// ==> gen code
-// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123
-//*/
-//
-////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123
-////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123
-//
-////@RequestScoped
-//@FormAuthenticationMechanismDefinition(
-// loginToContinue = @LoginToContinue(
-// loginPage = "/login-servlet",
-// errorPage = "/login-error-servlet"
-// )
-//)
-//@WebServlet({"/authorize"})
-//@ServletSecurity(@HttpConstraint(rolesAllowed = "user"))
-////@Stateless
-//@RequestScoped
-//public class AuthorizationEndpoint extends HttpServlet {
-//
-// private static final List authorizedResponseTypes = Arrays.asList("code", "token");
-//
-// @Inject
-// private SecurityContext securityContext;
-//
-// @PersistenceContext(name = "jpa-oauth2-pu")
-// private EntityManager entityManager;
-//
-// @EJB
-// private AuthCodeService authCodeService;
-//
-// //HTTP GET IS A MUST, POST IS OPTIONAL
-// @Override
-// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-//
-// String error = "";
-//
-// //1. User Authentication
-// Principal principal = securityContext.getCallerPrincipal();
-//
-// //2. Check for a valid client_id
-// String clientId = request.getParameter("client_id");
-// if (clientId == null) {
-// request.setAttribute("error", "The client " + clientId + " doesn't exist.");
-// }
-// request.setAttribute("clientId", clientId);
-// Client client = entityManager.find(Client.class, clientId);
-// if (client == null) {
-// request.setAttribute("error", "The client " + clientId + " doesn't exist.");
-// }
-//
-// //3. check for a valid response_type
-// String responseType = request.getParameter("response_type");
-// if (!authorizedResponseTypes.contains(responseType)) {
-// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes;
-// request.setAttribute("error", error);
-// request.getRequestDispatcher("/error.jsp")
-// .forward(request, response);
-// }
-//
-// //4. Optional redirect_uri, if provided should match
-// String redirectUri = request.getParameter("redirect_uri");
-// checkRedirectUri(client, redirectUri);
-//
-// //save params
-// String currentUri = request.getRequestURI();
-// request.setAttribute("post_redirect_uri", currentUri);
-//
-// String state = request.getParameter("state");
-// Map requestMap = new HashMap<>();
-// requestMap.put("response_type", responseType);
-// requestMap.put("client_id", clientId);
-// requestMap.put("redirect_uri", redirectUri);
-// requestMap.put("state", state);
-// request.setAttribute("requestMap", requestMap);
-//
-// //5.scope: Optional
-// String requestedScope = request.getParameter("scope");
-// if (requestedScope.isEmpty()) {
-// requestedScope = client.getScope();
-// }
-// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes)
-// //checkRequestedScope(requestedScope, client.getScope());
-//
-// //sub set of user scope
-// //allowed scope by the user
-//
-// User user = entityManager.find(User.class, principal.getName());
-// request.setAttribute("scopes", requestedScope);
-//
-//
-// forward("/authorize.jsp", request, response);
-// }
-//
-// @Override
-// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-// String clientId = request.getParameter("client_id");
-//
-// String responseType = request.getParameter("response_type");
-// if (!authorizedResponseTypes.contains(responseType)) {
-// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes;
-// request.setAttribute("error", error);
-// forward("/error.jsp", request, response);
-// }
-//
-// Client client = entityManager.find(Client.class, clientId);
-// Objects.requireNonNull(client);
-//
-// String userId = securityContext.getCallerPrincipal().getName();
-// AuthorizationCode authorizationCode = new AuthorizationCode();
-// authorizationCode.setClientId(clientId);
-// authorizationCode.setUserId(userId);
-// String redirectUri = request.getParameter("redirect_uri");
-// authorizationCode.setRedirectUri(redirectUri);
-//
-// redirectUri = checkRedirectUri(client, redirectUri);
-//
-// String[] scope = request.getParameterValues("scope");
-// if (scope == null) {
-// request.setAttribute("error", "User doesn't approved any scope");
-// forward("/error.jsp", request, response);
-// }
-//
-// String approvedScopes = String.join(" ", scope);
-// authorizationCode.setApprovedScopes(approvedScopes);
-//
-// //entityManager.persist(authorizationCode);
-// authCodeService.save(authorizationCode);
-// String code = authorizationCode.getCode();
-//
-// StringBuilder sb = new StringBuilder(redirectUri);
-// sb.append("?code=").append(code);
-//
-// //If the client send a state, Send it back
-// String state = request.getParameter("state");
-// if (state != null) {
-// sb.append("&state=").append(state);
-// }
-// response.sendRedirect(sb.toString());
-// }
-//
-// private String checkRedirectUri(Client client, String redirectUri) {
-// //redirect uri
-// if (redirectUri == null) {
-// //erreur: param redirect_uri && client redirect_uri don't match.
-// redirectUri = client.getRedirectUri();
-// if (redirectUri == null) {
-// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri.");
-// }
-// } else if (!redirectUri.equals(client.getRedirectUri())) {
-// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match.");
-// }
-// return redirectUri;
-// }
-//
-// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-// request.getRequestDispatcher(path)
-// .forward(request, response);
-// }
-//}
diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java
deleted file mode 100644
index 73085a68d1..0000000000
--- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java
+++ /dev/null
@@ -1,70 +0,0 @@
-//package com.baeldung.security.oauth2.server.web;
-//
-//import AuthorizationGrantTypeHandler;
-//import TokenResponse;
-//import com.baeldung.security.oauth2.server.security.Authenticated;
-//import com.nimbusds.jose.JOSEException;
-//
-//import javax.enterprise.inject.Instance;
-//import javax.enterprise.inject.literal.NamedLiteral;
-//import javax.inject.Inject;
-//import javax.security.enterprise.SecurityContext;
-//import javax.ws.rs.Consumes;
-//import javax.ws.rs.POST;
-//import javax.ws.rs.Path;
-//import javax.ws.rs.Produces;
-//import javax.ws.rs.core.MediaType;
-//import javax.ws.rs.core.MultivaluedMap;
-//import javax.ws.rs.core.Response;
-//import java.security.Principal;
-//import java.util.Arrays;
-//import java.util.List;
-//import java.util.Objects;
-//
-///**
-// * {
-// * "access_token" : "acb6803a48114d9fb4761e403c17f812",
-// * "token_type" : "bearer",
-// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ",
-// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r",
-// * "expires_in" : 43199,
-// * "scope" : "openid oauth.approvals",
-// * "jti" : "acb6803a48114d9fb4761e403c17f812"
-// * }
-// */
-//@Path("token")
-//public class TokenEndpoint {
-//
-// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials");
-//
-// @Inject
-// private SecurityContext securityContext;
-//
-// @Inject
-// Instance authorizationGrantTypeHandlers;
-//
-// @POST
-// @Produces(MediaType.APPLICATION_JSON)
-// @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-// @Authenticated
-// public Response token(MultivaluedMap params) throws JOSEException {
-// //Authenticate client with [basic] http authentication mechanism
-// Principal principal = securityContext.getCallerPrincipal();
-// Objects.requireNonNull(principal, "Client not authenticated!");
-//
-// //Check grant_type params
-// String grantType = params.getFirst("grant_type");
-// Objects.requireNonNull(grantType, "grant_type params is required");
-// //authorization_code, password, refresh, client_credentials
-// if (!supportedGrantTypes.contains(grantType)) {
-// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes);
-// }
-// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
-// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params);
-// Response response = Response.ok(tokenResponse)
-// .header("Cache-Control", "no-store")
-// .header("Pragma", "no-cache")
-// .build();
-// return response;
-// }
-//}
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")}
+
+
+