Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-15959
This commit is contained in:
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public final class NaturalOrderComparators {
|
||||
|
||||
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
|
||||
|
||||
private NaturalOrderComparators() {
|
||||
throw new AssertionError("Let's keep this static");
|
||||
}
|
||||
|
||||
public static Comparator<String> createNaturalOrderRegexComparator() {
|
||||
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
|
||||
}
|
||||
|
||||
private static double parseStringToNumber(String input){
|
||||
|
||||
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
|
||||
|
||||
if("".equals(digitsOnly)) return 0;
|
||||
|
||||
try{
|
||||
return Double.parseDouble(digitsOnly);
|
||||
}catch (NumberFormatException nfe){
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.algorithms.stringsortingbynumber;
|
||||
|
||||
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NaturalOrderComparatorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
|
||||
|
||||
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
|
||||
List<String> expected = new ArrayList<>(testStrings);
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-7
@@ -18,12 +18,6 @@
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-spring-boot-starter</artifactId>
|
||||
<version>${axon.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-server-connector</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -58,7 +52,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<axon.version>4.0.3</axon.version>
|
||||
<axon.version>4.1.2</axon.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -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() {
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -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<String, OrderedProduct> orderedProducts = new HashMap<>();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
spring.application.name=Order Management Service
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.array.looping;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LoopDiagonallyTest {
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
+16
-22
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+18
-12
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,20 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-networking-2</artifactId>
|
||||
<name>core-java-networking-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-networking-2</finalName>
|
||||
</build>
|
||||
</project>
|
||||
+25
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
<module>pre-jpms</module>
|
||||
<module>core-java-exceptions</module>
|
||||
<module>core-java-optional</module>
|
||||
<module>core-java-networking-2</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToLowerCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignUppercase = "\u0049";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
|
||||
assertEquals("john doe", name.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0069", foreignUppercase.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.string.changecase;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ToUpperCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignLowercase = "\u0069";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
|
||||
assertEquals("JOHN DOE", name.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0049", foreignLowercase.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp)
|
||||
|
||||
|
||||
+2
-2
@@ -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.")
|
||||
|
||||
+28
-20
@@ -15,15 +15,14 @@ import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Path("token")
|
||||
public class TokenEndpoint {
|
||||
|
||||
List<String> supportedGrantTypes = Collections.singletonList("authorization_code");
|
||||
List<String> supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token");
|
||||
|
||||
@Inject
|
||||
private AppDataRepository appDataRepository;
|
||||
@@ -39,36 +38,36 @@ public class TokenEndpoint {
|
||||
|
||||
//Check grant_type params
|
||||
String grantType = params.getFirst("grant_type");
|
||||
Objects.requireNonNull(grantType, "grant_type params is required");
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "unsupported_grant_type")
|
||||
.add("error_description", "grant type should be one of :" + supportedGrantTypes)
|
||||
.build();
|
||||
return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity(error).build();
|
||||
if (grantType == null || grantType.isEmpty())
|
||||
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
|
||||
|
||||
if (!supportedGrantTypes.contains(grantType)) {
|
||||
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
//Client Authentication
|
||||
String[] clientCredentials = extract(authHeader);
|
||||
if (clientCredentials.length != 2) {
|
||||
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientId = clientCredentials[0];
|
||||
String clientSecret = clientCredentials[1];
|
||||
Client client = appDataRepository.getClient(clientId);
|
||||
if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "invalid_client")
|
||||
.build();
|
||||
return Response.status(Response.Status.UNAUTHORIZED)
|
||||
.entity(error).build();
|
||||
if (client == null) {
|
||||
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String clientSecret = clientCredentials[1];
|
||||
if (!clientSecret.equals(client.getClientSecret())) {
|
||||
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
|
||||
JsonObject tokenResponse = null;
|
||||
try {
|
||||
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
|
||||
} catch (WebApplicationException e) {
|
||||
return e.getResponse();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return Response.ok(tokenResponse)
|
||||
@@ -81,6 +80,15 @@ public class TokenEndpoint {
|
||||
if (authHeader != null && authHeader.startsWith("Basic ")) {
|
||||
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
|
||||
}
|
||||
return null;
|
||||
return new String[]{};
|
||||
}
|
||||
|
||||
private Response responseError(String error, String errorDescription, Response.Status status) {
|
||||
JsonObject errorResponse = Json.createObjectBuilder()
|
||||
.add("error", error)
|
||||
.add("error_description", errorDescription)
|
||||
.build();
|
||||
return Response.status(status)
|
||||
.entity(errorResponse).build();
|
||||
}
|
||||
}
|
||||
|
||||
+87
@@ -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();
|
||||
}
|
||||
}
|
||||
+4
-49
@@ -1,18 +1,7 @@
|
||||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.baeldung.oauth2.authorization.server.PEMKeyUtils;
|
||||
import com.baeldung.oauth2.authorization.server.model.AuthorizationCode;
|
||||
import com.nimbusds.jose.JOSEObjectType;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.JWSHeader;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.eclipse.microprofile.config.Config;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
@@ -20,22 +9,14 @@ import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Named("authorization_code")
|
||||
public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler {
|
||||
public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Inject
|
||||
private Config config;
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
//1. code is required
|
||||
@@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType
|
||||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//JWT Header
|
||||
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
|
||||
|
||||
Instant now = Instant.now();
|
||||
Long expiresInMin = 30L;
|
||||
Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
|
||||
|
||||
//3. JWT Payload or claims
|
||||
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
|
||||
.issuer("http://localhost:9080")
|
||||
.subject(authorizationCode.getUserId())
|
||||
.claim("upn", authorizationCode.getUserId())
|
||||
.audience("http://localhost:9280")
|
||||
.claim("scope", authorizationCode.getApprovedScopes())
|
||||
.claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" ")))
|
||||
.expirationTime(expiresIn) // expires in 30 minutes
|
||||
.notBeforeTime(Date.from(now))
|
||||
.issueTime(Date.from(now))
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
|
||||
|
||||
//4. Signing
|
||||
String signingkey = config.getValue("signingkey", String.class);
|
||||
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
|
||||
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
|
||||
signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey()));
|
||||
|
||||
//5. Finally the JWT access token
|
||||
String accessToken = signedJWT.serialize();
|
||||
String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes());
|
||||
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", authorizationCode.getApprovedScopes())
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.oauth2.authorization.server.handler;
|
||||
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
import javax.inject.Named;
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Named("refresh_token")
|
||||
public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler {
|
||||
|
||||
@Override
|
||||
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
|
||||
String refreshToken = params.getFirst("refresh_token");
|
||||
if (refreshToken == null || "".equals(refreshToken)) {
|
||||
throw new WebApplicationException("invalid_grant");
|
||||
}
|
||||
|
||||
//Decode refresh token
|
||||
SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
|
||||
JWSVerifier verifier = getJWSVerifier();
|
||||
|
||||
if (!signedRefreshToken.verify(verifier)) {
|
||||
throw new WebApplicationException("Invalid refresh token.");
|
||||
}
|
||||
if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
|
||||
throw new WebApplicationException("Refresh token expired.");
|
||||
}
|
||||
String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
|
||||
if (!clientId.equals(refreshTokenClientId)) {
|
||||
throw new WebApplicationException("Invalid client_id.");
|
||||
}
|
||||
|
||||
//At this point, the refresh token is valid and not yet expired
|
||||
//So create a new access token from it.
|
||||
String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
|
||||
String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");
|
||||
|
||||
String requestedScopes = params.getFirst("scope");
|
||||
if (requestedScopes != null && !requestedScopes.isEmpty()) {
|
||||
Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
|
||||
Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
|
||||
if (!aScopes.containsAll(rScopes)) {
|
||||
JsonObject error = Json.createObjectBuilder()
|
||||
.add("error", "Invalid_request")
|
||||
.add("error_description", "Requested scopes should be a subset of the original scopes.")
|
||||
.build();
|
||||
Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
|
||||
throw new WebApplicationException(response);
|
||||
}
|
||||
} else {
|
||||
requestedScopes = approvedScopes;
|
||||
}
|
||||
|
||||
String accessToken = getAccessToken(clientId, subject, requestedScopes);
|
||||
return Json.createObjectBuilder()
|
||||
.add("token_type", "Bearer")
|
||||
.add("access_token", accessToken)
|
||||
.add("expires_in", expiresInMin * 60)
|
||||
.add("scope", requestedScopes)
|
||||
.add("refresh_token", refreshToken)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -41,8 +41,8 @@
|
||||
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<input type="submit" name="approbation_status" value="YES"/>
|
||||
<input type="submit" name="approbation_status" value="NO"/>
|
||||
<input type="submit" name="approval_status" value="YES"/>
|
||||
<input type="submit" name="approval_status" value="NO"/>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+23
@@ -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;
|
||||
}
|
||||
}
|
||||
+13
-22
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user