Merge branch 'eugenp:master' into master
This commit is contained in:
commit
017e4e7582
@ -0,0 +1,123 @@
|
|||||||
|
package com.baeldung.algorithms.stringrotation;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Queue;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class StringRotation {
|
||||||
|
|
||||||
|
public static boolean doubledOriginContainsRotation(String origin, String rotation) {
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
return origin.concat(origin)
|
||||||
|
.contains(rotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
|
||||||
|
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
|
||||||
|
List<Integer> indexes = IntStream.range(0, origin.length())
|
||||||
|
.filter(i -> rotation.charAt(i) == origin.charAt(0))
|
||||||
|
.boxed()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
for (int startingAt : indexes) {
|
||||||
|
if (isRotation(startingAt, rotation, origin)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean isRotation(int startingAt, String rotation, String origin) {
|
||||||
|
|
||||||
|
for (int i = 0; i < origin.length(); i++) {
|
||||||
|
if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isRotationUsingQueue(String origin, String rotation) {
|
||||||
|
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
return checkWithQueue(origin, rotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean checkWithQueue(String origin, String rotation) {
|
||||||
|
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
|
||||||
|
Queue<Character> originQueue = getCharactersQueue(origin);
|
||||||
|
|
||||||
|
Queue<Character> rotationQueue = getCharactersQueue(rotation);
|
||||||
|
|
||||||
|
int k = rotation.length();
|
||||||
|
while (k > 0 && null != rotationQueue.peek()) {
|
||||||
|
k--;
|
||||||
|
char ch = rotationQueue.peek();
|
||||||
|
rotationQueue.remove();
|
||||||
|
rotationQueue.add(ch);
|
||||||
|
if (rotationQueue.equals(originQueue)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Queue<Character> getCharactersQueue(String origin) {
|
||||||
|
return origin.chars()
|
||||||
|
.mapToObj(c -> (char) c)
|
||||||
|
.collect(Collectors.toCollection(LinkedList::new));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
|
||||||
|
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
return checkPrefixAndSuffix(origin, rotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean checkPrefixAndSuffix(String origin, String rotation) {
|
||||||
|
if (origin.length() == rotation.length()) {
|
||||||
|
|
||||||
|
for (int i = 0; i < origin.length(); i++) {
|
||||||
|
if (origin.charAt(i) == rotation.charAt(0)) {
|
||||||
|
if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
|
||||||
|
if (checkOriginPrefixWithRotationSuffix(origin, rotation, i))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
|
||||||
|
return origin.substring(i)
|
||||||
|
.equals(rotation.substring(0, origin.length() - i));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
|
||||||
|
return origin.substring(0, i)
|
||||||
|
.equals(rotation.substring(origin.length() - i));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.algorithms.stringrotation;
|
||||||
|
|
||||||
|
import static com.baeldung.algorithms.stringrotation.StringRotation.doubledOriginContainsRotation;
|
||||||
|
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingCommonStartWithOrigin;
|
||||||
|
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingQueue;
|
||||||
|
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingSuffixAndPrefix;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class StringRotationUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenIsRotation() {
|
||||||
|
assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
|
||||||
|
assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenNoRotation() {
|
||||||
|
assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
|
||||||
|
assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
|
||||||
|
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
|
||||||
|
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
|
||||||
|
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
|
||||||
|
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
|
||||||
|
assertTrue(isRotationUsingQueue("abcd", "cdab"));
|
||||||
|
assertTrue(isRotationUsingQueue("abcd", "abcd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
|
||||||
|
assertFalse(isRotationUsingQueue("abcd", "bbbb"));
|
||||||
|
assertFalse(isRotationUsingQueue("abcd", "abcde"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
|
||||||
|
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
|
||||||
|
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
|
||||||
|
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
|
||||||
|
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
|
||||||
|
}
|
||||||
|
}
|
@ -10,4 +10,6 @@
|
|||||||
<root level="INFO">
|
<root level="INFO">
|
||||||
<appender-ref ref="STDOUT" />
|
<appender-ref ref="STDOUT" />
|
||||||
</root>
|
</root>
|
||||||
|
|
||||||
|
<logger name="org.apache.camel.impl.engine" level="WARN"/>
|
||||||
</configuration>
|
</configuration>
|
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
<logger name="ch.qos.logback.classic.joran.action" level="WARN"/>
|
||||||
|
</configuration>
|
@ -1,61 +1,71 @@
|
|||||||
package com.baeldung.io
|
package com.baeldung.io
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
import groovy.io.FileType
|
import groovy.io.FileType
|
||||||
import groovy.io.FileVisitResult
|
import groovy.io.FileVisitResult
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue
|
||||||
|
|
||||||
class TraverseFileTreeUnitTest {
|
class TraverseFileTreeUnitTest {
|
||||||
@Test
|
@Test
|
||||||
void whenUsingEachFile_filesAreListed() {
|
void whenUsingEachFile_filesAreListed() {
|
||||||
|
var files = []
|
||||||
new File('src/main/resources').eachFile { file ->
|
new File('src/main/resources').eachFile { file ->
|
||||||
println file.name
|
files.add(file.name)
|
||||||
}
|
}
|
||||||
|
assertTrue(files.size() > 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = IllegalArgumentException)
|
@Test(expected = IllegalArgumentException)
|
||||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||||
|
var files = []
|
||||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||||
println file.name
|
files.add(file.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingEachFileMatch_filesAreListed() {
|
void whenUsingEachFileMatch_filesAreListed() {
|
||||||
|
var files = []
|
||||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||||
println file.name
|
files.add(file.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||||
|
var files = []
|
||||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||||
println "$file.parent $file.name"
|
files.add("$file.parent $file.name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||||
|
var files = []
|
||||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||||
println "$file.parent $file.name"
|
files.add("$file.parent $file.name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||||
|
var files = []
|
||||||
new File('src/main').eachDirRecurse { dir ->
|
new File('src/main').eachDirRecurse { dir ->
|
||||||
println "$dir.parent $dir.name"
|
files.add("$dir.parent $dir.name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||||
|
var files = []
|
||||||
new File('src/main').traverse { file ->
|
new File('src/main').traverse { file ->
|
||||||
if (file.directory && file.name == 'groovy') {
|
if (file.directory && file.name == 'groovy') {
|
||||||
FileVisitResult.SKIP_SUBTREE
|
FileVisitResult.SKIP_SUBTREE
|
||||||
} else {
|
} else {
|
||||||
println "$file.parent - $file.name"
|
files.add("$file.parent - $file.name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
assertTrue(files.size() > 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,8 @@ package groovy.com.baeldung.stringtypes
|
|||||||
|
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse
|
||||||
|
|
||||||
class DollarSlashyString {
|
class DollarSlashyString {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -19,6 +21,7 @@ class DollarSlashyString {
|
|||||||
- $/$$
|
- $/$$
|
||||||
/$
|
/$
|
||||||
|
|
||||||
print(dollarSlashy)
|
//print(dollarSlashy)
|
||||||
|
assertFalse(dollarSlashy.isEmpty())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.simplewebserver;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.Filter;
|
||||||
|
import com.sun.net.httpserver.Headers;
|
||||||
|
import com.sun.net.httpserver.HttpHandler;
|
||||||
|
import com.sun.net.httpserver.HttpHandlers;
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import com.sun.net.httpserver.Request;
|
||||||
|
import com.sun.net.httpserver.SimpleFileServer;
|
||||||
|
|
||||||
|
public class WebServer {
|
||||||
|
|
||||||
|
private final InetSocketAddress address = new InetSocketAddress(8080);
|
||||||
|
private final Path path = Path.of("/");
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
WebServer webServer = new WebServer();
|
||||||
|
HttpServer server = webServer.createWithHandler401Response();
|
||||||
|
server.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpServer createBasic() {
|
||||||
|
return SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpServer createWithHandler() throws IOException {
|
||||||
|
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||||
|
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||||
|
server.createContext("/test", handler);
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpServer createWithHandler401Response() {
|
||||||
|
Predicate<Request> findAllowedPath = r -> r.getRequestURI()
|
||||||
|
.getPath()
|
||||||
|
.equals("/test/allowed");
|
||||||
|
|
||||||
|
HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome");
|
||||||
|
HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
|
||||||
|
|
||||||
|
HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);
|
||||||
|
|
||||||
|
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||||
|
server.createContext("/test", handler);
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpServer createWithFilter() throws IOException {
|
||||||
|
Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);
|
||||||
|
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||||
|
return HttpServer.create(new InetSocketAddress(8080), 10, "/test", handler, filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -60,14 +60,15 @@ public class HashtableUnitTest {
|
|||||||
table.put(new Word("dog"), "another animal");
|
table.put(new Word("dog"), "another animal");
|
||||||
|
|
||||||
Iterator<Word> it = table.keySet().iterator();
|
Iterator<Word> it = table.keySet().iterator();
|
||||||
System.out.println("iterator created");
|
// System.out.println("iterator created");
|
||||||
|
|
||||||
table.remove(new Word("dog"));
|
table.remove(new Word("dog"));
|
||||||
System.out.println("element removed");
|
// System.out.println("element removed");
|
||||||
|
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
Word key = it.next();
|
Word key = it.next();
|
||||||
System.out.println(table.get(key));
|
// System.out.println(table.get(key));
|
||||||
|
assertNotNull(table.get(key));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,12 +86,13 @@ public class HashtableUnitTest {
|
|||||||
table.put(new Word("8"), "eight");
|
table.put(new Word("8"), "eight");
|
||||||
|
|
||||||
Enumeration<Word> enumKey = table.keys();
|
Enumeration<Word> enumKey = table.keys();
|
||||||
System.out.println("Enumeration created");
|
// System.out.println("Enumeration created");
|
||||||
table.remove(new Word("1"));
|
table.remove(new Word("1"));
|
||||||
System.out.println("element removed");
|
// System.out.println("element removed");
|
||||||
while (enumKey.hasMoreElements()) {
|
while (enumKey.hasMoreElements()) {
|
||||||
Word key = enumKey.nextElement();
|
Word key = enumKey.nextElement();
|
||||||
System.out.println(table.get(key));
|
// System.out.println(table.get(key));
|
||||||
|
assertNotNull(table.get(key));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -110,7 +112,8 @@ public class HashtableUnitTest {
|
|||||||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||||
while (it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
Map.Entry<Word, String> entry = it.next();
|
Map.Entry<Word, String> entry = it.next();
|
||||||
System.out.println(entry.getValue());
|
// System.out.println(entry.getValue());
|
||||||
|
assertNotNull(entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,79 @@
|
|||||||
|
package com.baeldung.runvssupply;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
public class RunAndSupplyCompare {
|
||||||
|
|
||||||
|
public static void main(String args[]) throws ExecutionException, InterruptedException {
|
||||||
|
chainingOperationCompare();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void inputAndReturnCompare() throws ExecutionException, InterruptedException {
|
||||||
|
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||||
|
// Perform non-result producing task
|
||||||
|
System.out.println("Task executed asynchronously");
|
||||||
|
});
|
||||||
|
|
||||||
|
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
// Perform result-producing task
|
||||||
|
return "Result of the asynchronous computation";
|
||||||
|
});
|
||||||
|
// Get the result later
|
||||||
|
String result = supplyAsyncFuture.get();
|
||||||
|
System.out.println("Result: " + result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void exceptionHandlingCompare() {
|
||||||
|
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||||
|
// Task that may throw an exception
|
||||||
|
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
runAsyncFuture.get();
|
||||||
|
// Exception will be thrown here
|
||||||
|
} catch (ExecutionException ex) {
|
||||||
|
Throwable cause = ex.getCause();
|
||||||
|
System.out.println("Exception caught: " + cause.getMessage());
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
CompletableFuture<Object> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
// Task that may throw an exception
|
||||||
|
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||||
|
})
|
||||||
|
.exceptionally(ex -> {
|
||||||
|
// Exception handling logic
|
||||||
|
return "Default value";
|
||||||
|
});
|
||||||
|
|
||||||
|
Object result = supplyAsyncFuture.join();
|
||||||
|
// Get the result or default value
|
||||||
|
System.out.println("Result: " + result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void chainingOperationCompare() {
|
||||||
|
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||||
|
// Perform non-result producing task
|
||||||
|
System.out.println("Task executed asynchronously");
|
||||||
|
});
|
||||||
|
runAsyncFuture.thenRun(() -> {
|
||||||
|
// Execute another task after the completion of runAsync()
|
||||||
|
System.out.println("Another task executed after runAsync() completes");
|
||||||
|
});
|
||||||
|
|
||||||
|
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
// Perform result-producing task
|
||||||
|
return "Result of the asynchronous computation";
|
||||||
|
});
|
||||||
|
supplyAsyncFuture.thenApply(result -> {
|
||||||
|
// Transform the result
|
||||||
|
return result.toUpperCase();
|
||||||
|
})
|
||||||
|
.thenAccept(transformedResult -> {
|
||||||
|
// Consume the transformed result
|
||||||
|
System.out.println("Transformed Result: " + transformedResult);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,91 @@
|
|||||||
|
package com.baeldung.concurrent.applyvsapplyasync;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
public class ThenApplyAndThenApplyAsyncUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenUsingThenApply_thenResultIsAsExpected() {
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||||
|
CompletableFuture<String> thenApplyResultFuture = future.thenApply(num -> "Result: " + num);
|
||||||
|
|
||||||
|
String thenApplyResult = thenApplyResultFuture.join();
|
||||||
|
assertEquals("Result: 5", thenApplyResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenUsingThenApplyAsync_thenResultIsAsExpected() {
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||||
|
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num);
|
||||||
|
|
||||||
|
String thenApplyAsyncResult = thenApplyAsyncResultFuture.join();
|
||||||
|
assertEquals("Result: 5", thenApplyAsyncResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsPropagated() {
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||||
|
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||||
|
assertThrows(CompletionException.class, () -> resultFuture.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsHandledAsExpected() {
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||||
|
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||||
|
try {
|
||||||
|
// Accessing the result
|
||||||
|
String result = resultFuture.join();
|
||||||
|
assertEquals("Result: 5", result);
|
||||||
|
} catch (CompletionException e) {
|
||||||
|
assertEquals("java.lang.ArithmeticException: / by zero", e.getMessage());
|
||||||
|
System.err.println("Exception caught: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenUsingThenApplyAsync_thenExceptionIsHandledAsExpected() {
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||||
|
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num / 0);
|
||||||
|
|
||||||
|
String result = thenApplyAsyncResultFuture.handle((res, error) -> {
|
||||||
|
if (error != null) {
|
||||||
|
// Handle the error appropriately, e.g., return a default value
|
||||||
|
return "Error occurred";
|
||||||
|
} else {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.join(); // Now join() won't throw the exception
|
||||||
|
assertEquals("Error occurred", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFutureWithExecutor_whenUsingThenApplyAsync_thenThreadExecutesAsExpected() {
|
||||||
|
ExecutorService customExecutor = Executors.newFixedThreadPool(4);
|
||||||
|
|
||||||
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
|
||||||
|
try {
|
||||||
|
Thread.sleep(2000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return 5;
|
||||||
|
}, customExecutor);
|
||||||
|
|
||||||
|
CompletableFuture<String> resultFuture = future.thenApplyAsync(num -> "Result: " + num, customExecutor);
|
||||||
|
|
||||||
|
String result = resultFuture.join();
|
||||||
|
assertEquals("Result: 5", result);
|
||||||
|
|
||||||
|
customExecutor.shutdown();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -4,7 +4,7 @@ import java.util.function.Function;
|
|||||||
|
|
||||||
public class Currying {
|
public class Currying {
|
||||||
|
|
||||||
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
|
private static Function<Double, Function<Double, Double>> weight = gravity -> mass -> mass * gravity;
|
||||||
|
|
||||||
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
||||||
|
|
||||||
|
@ -0,0 +1,16 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
<logger name="org.eclipse.jetty.server.handler" level="WARN"/>
|
||||||
|
<logger name="org.mockserver.log" level="WARN"/>
|
||||||
|
</configuration>
|
@ -23,9 +23,9 @@ public class SSLDebugLogger {
|
|||||||
|
|
||||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||||
String line;
|
String line;
|
||||||
logger.info("Response from " + url + ":");
|
logger.debug("Response from " + url + ":");
|
||||||
while ((line = reader.readLine()) != null) {
|
while ((line = reader.readLine()) != null) {
|
||||||
logger.info(line);
|
logger.debug(line);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.string.chkstringinmirror;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class CheckStringEqualsMirrorReflectionUnitTest {
|
||||||
|
|
||||||
|
private final static Set<Character> SYMMETRIC_LETTERS = Set.of('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y');
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingIsReflectionEqual_thenGetExpectedResults() {
|
||||||
|
assertFalse(isMirrorImageEqual("LOL"));
|
||||||
|
assertFalse(isMirrorImageEqual("AXY"));
|
||||||
|
assertFalse(isMirrorImageEqual("HUHU"));
|
||||||
|
|
||||||
|
assertTrue(isMirrorImageEqual(""));
|
||||||
|
assertTrue(isMirrorImageEqual("AAA"));
|
||||||
|
assertTrue(isMirrorImageEqual("HUH"));
|
||||||
|
assertTrue(isMirrorImageEqual("HIMMIH"));
|
||||||
|
assertTrue(isMirrorImageEqual("HIMIH"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public boolean isMirrorImageEqual(String input) {
|
||||||
|
return containsOnlySymmetricLetters(input) && isPalindrome(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean containsOnlySymmetricLetters(String input) {
|
||||||
|
Set<Character> characterSet = input.chars()
|
||||||
|
.mapToObj(c -> (char) c)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
characterSet.removeAll(SYMMETRIC_LETTERS);
|
||||||
|
return characterSet.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPalindrome(String input) {
|
||||||
|
String reversed = new StringBuilder(input).reverse()
|
||||||
|
.toString();
|
||||||
|
return input.equals(reversed);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.finduniqueemails;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class FindUniqueEmailsUnitTest {
|
||||||
|
String[] emailList = {"user@example.com", "user@example.com", "user@gmail.com", "admin@example.com", "USER@example.com"};
|
||||||
|
Set<String> expectedUniqueEmails = new HashSet<>();
|
||||||
|
|
||||||
|
FindUniqueEmailsUnitTest() {
|
||||||
|
expectedUniqueEmails.add("user@example.com");
|
||||||
|
expectedUniqueEmails.add("user@gmail.com");
|
||||||
|
expectedUniqueEmails.add("admin@example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmailList_whenUsingStringManipulation_thenFindUniqueEmails() {
|
||||||
|
Set<String> uniqueEmails = new HashSet<>();
|
||||||
|
for (String email : emailList) {
|
||||||
|
uniqueEmails.add(email.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(expectedUniqueEmails, uniqueEmails);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmailList_whenUsingJavaStreams_thenFindUniqueEmails() {
|
||||||
|
Set<String> uniqueEmails = Arrays.stream(emailList)
|
||||||
|
.map(String::toLowerCase)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
assertEquals(expectedUniqueEmails, uniqueEmails);
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
FROM openjdk:11
|
FROM openjdk:17-alpine
|
||||||
MAINTAINER baeldung.com
|
MAINTAINER baeldung.com
|
||||||
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
|
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
|
||||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||||
|
@ -8,9 +8,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-boot-2</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-boot-2</relativePath>
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.javatypefromclassinjava;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JavaType;
|
||||||
|
import com.fasterxml.jackson.databind.type.TypeFactory;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
public class JavaTypeFromClassUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGenericClass_whenCreatingJavaType_thenJavaTypeNotNull() {
|
||||||
|
Class<?> myClass = MyGenericClass.class;
|
||||||
|
|
||||||
|
JavaType javaType = TypeFactory.defaultInstance().constructType(myClass);
|
||||||
|
|
||||||
|
assertNotNull(javaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenParametricType_whenCreatingJavaType_thenJavaTypeNotNull() {
|
||||||
|
Class<?> containerClass = Container.class;
|
||||||
|
Class<?> elementType = String.class;
|
||||||
|
|
||||||
|
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(containerClass, elementType);
|
||||||
|
|
||||||
|
assertNotNull(javaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
static class MyGenericClass<T> {
|
||||||
|
// Class implementation
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Container<T> {
|
||||||
|
// Class implementation
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -95,6 +95,12 @@
|
|||||||
<artifactId>protobuf-java</artifactId>
|
<artifactId>protobuf-java</artifactId>
|
||||||
<version>${google-protobuf.version}</version>
|
<version>${google-protobuf.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- jetcd core api -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.etcd</groupId>
|
||||||
|
<artifactId>jetcd-core</artifactId>
|
||||||
|
<version>${jetcd-version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
@ -110,6 +116,7 @@
|
|||||||
<yamlbeans.version>1.15</yamlbeans.version>
|
<yamlbeans.version>1.15</yamlbeans.version>
|
||||||
<apache-thrift.version>0.14.2</apache-thrift.version>
|
<apache-thrift.version>0.14.2</apache-thrift.version>
|
||||||
<google-protobuf.version>3.17.3</google-protobuf.version>
|
<google-protobuf.version>3.17.3</google-protobuf.version>
|
||||||
|
<jetcd-version>0.7.7</jetcd-version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.etcd;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
import io.etcd.jetcd.kv.GetResponse;
|
||||||
|
import io.etcd.jetcd.ByteSequence;
|
||||||
|
import io.etcd.jetcd.KV;
|
||||||
|
import io.etcd.jetcd.Client;
|
||||||
|
|
||||||
|
public class JetcdExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String etcdEndpoint = "http://localhost:2379";
|
||||||
|
ByteSequence key = ByteSequence.from("/mykey".getBytes());
|
||||||
|
ByteSequence value = ByteSequence.from("Hello, etcd!".getBytes());
|
||||||
|
|
||||||
|
try (Client client = Client.builder().endpoints(etcdEndpoint).build()) {
|
||||||
|
KV kvClient = client.getKVClient();
|
||||||
|
|
||||||
|
// Put a key-value pair
|
||||||
|
kvClient.put(key, value).get();
|
||||||
|
|
||||||
|
// Retrieve the value using CompletableFuture
|
||||||
|
CompletableFuture<GetResponse> getFuture = kvClient.get(key);
|
||||||
|
GetResponse response = getFuture.get();
|
||||||
|
|
||||||
|
// Delete the key
|
||||||
|
kvClient.delete(key).get();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -48,6 +48,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.activemq</groupId>
|
<groupId>org.apache.activemq</groupId>
|
||||||
<artifactId>artemis-jms-server</artifactId>
|
<artifactId>artemis-jms-server</artifactId>
|
||||||
|
<version>${activemq.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
@ -65,4 +66,8 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<activemq.version>2.32.0</activemq.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -229,8 +229,8 @@
|
|||||||
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
|
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
|
||||||
<maven-resources-plugin.version>3.3.0</maven-resources-plugin.version>
|
<maven-resources-plugin.version>3.3.0</maven-resources-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
||||||
<spring-boot.version>3.2.2</spring-boot.version>
|
<spring-boot.version>3.1.5</spring-boot.version>
|
||||||
<junit-jupiter.version>5.10.2</junit-jupiter.version>
|
<junit-jupiter.version>5.8.2</junit-jupiter.version>
|
||||||
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.version>
|
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.version>
|
||||||
<logback.version>1.4.4</logback.version>
|
<logback.version>1.4.4</logback.version>
|
||||||
<slf4j.version>2.0.3</slf4j.version>
|
<slf4j.version>2.0.3</slf4j.version>
|
||||||
|
@ -108,7 +108,7 @@
|
|||||||
<module>spring-jpa-2</module>
|
<module>spring-jpa-2</module>
|
||||||
<module>spring-jdbc</module>
|
<module>spring-jdbc</module>
|
||||||
<module>spring-jdbc-2</module>
|
<module>spring-jdbc-2</module>
|
||||||
<module>spring-jooq</module>
|
<!--<module>spring-jooq</module>-->
|
||||||
<module>spring-mybatis</module>
|
<module>spring-mybatis</module>
|
||||||
<module>spring-persistence-simple</module>
|
<module>spring-persistence-simple</module>
|
||||||
<module>spring-data-yugabytedb</module>
|
<module>spring-data-yugabytedb</module>
|
||||||
|
@ -62,6 +62,11 @@
|
|||||||
<artifactId>modelmapper</artifactId>
|
<artifactId>modelmapper</artifactId>
|
||||||
<version>${modelmapper.version}</version>
|
<version>${modelmapper.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
@ -88,6 +93,7 @@
|
|||||||
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
||||||
<jackson.version>2.16.0</jackson.version>
|
<jackson.version>2.16.0</jackson.version>
|
||||||
<modelmapper.version>3.2.0</modelmapper.version>
|
<modelmapper.version>3.2.0</modelmapper.version>
|
||||||
|
<commons-codec.version>1.16.1</commons-codec.version>
|
||||||
<lombok.version>1.18.30</lombok.version>
|
<lombok.version>1.18.30</lombok.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class CustomFunctionApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(CustomFunctionApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.hibernate.boot.model.FunctionContributions;
|
||||||
|
import org.hibernate.dialect.H2Dialect;
|
||||||
|
|
||||||
|
import org.hibernate.query.sqm.function.FunctionKind;
|
||||||
|
import org.hibernate.query.sqm.function.SqmFunctionRegistry;
|
||||||
|
import org.hibernate.query.sqm.produce.function.PatternFunctionDescriptorBuilder;
|
||||||
|
import org.hibernate.type.spi.TypeConfiguration;
|
||||||
|
|
||||||
|
public class CustomH2Dialect extends H2Dialect {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void initializeFunctionRegistry(FunctionContributions functionContributions) {
|
||||||
|
super.initializeFunctionRegistry(functionContributions);
|
||||||
|
SqmFunctionRegistry registry = functionContributions.getFunctionRegistry();
|
||||||
|
TypeConfiguration types = functionContributions.getTypeConfiguration();
|
||||||
|
|
||||||
|
new PatternFunctionDescriptorBuilder(registry, "sha256hex", FunctionKind.NORMAL, "SHA256_HEX(?1)")
|
||||||
|
.setExactArgumentCount(1)
|
||||||
|
.setInvariantType(types.getBasicTypeForJavaType(String.class))
|
||||||
|
.register();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CustomHibernateConfig implements HibernatePropertiesCustomizer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void customize(Map<String, Object> hibernateProperties) {
|
||||||
|
hibernateProperties.put("hibernate.dialect", "com.baeldung.customfunc.CustomH2Dialect");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "product")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@EqualsAndHashCode(of = {"id"})
|
||||||
|
@NamedStoredProcedureQuery(
|
||||||
|
name = "Product.sha256Hex",
|
||||||
|
procedureName = "SHA256_HEX",
|
||||||
|
parameters = @StoredProcedureParameter(mode = ParameterMode.IN, name = "value", type = String.class)
|
||||||
|
)
|
||||||
|
public class Product {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "product_id")
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.jpa.repository.query.Procedure;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface ProductRepository extends JpaRepository<Product, Integer> {
|
||||||
|
|
||||||
|
@Procedure(name = "Product.sha256Hex")
|
||||||
|
String getSha256HexByNamedMapping(@Param("value") String value);
|
||||||
|
|
||||||
|
@Query(value = "CALL SHA256_HEX(:value)", nativeQuery = true)
|
||||||
|
String getSha256HexByNativeCall(@Param("value") String value);
|
||||||
|
|
||||||
|
@Query(value = "SELECT SHA256_HEX(name) FROM product", nativeQuery = true)
|
||||||
|
List<String> getProductNameListInSha256HexByNativeSelect();
|
||||||
|
|
||||||
|
@Query(value = "SELECT sha256Hex(p.name) FROM Product p")
|
||||||
|
List<String> getProductNameListInSha256Hex();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||||
|
|
||||||
|
@SpringBootTest(classes = CustomFunctionApplication.class, properties = {
|
||||||
|
"spring.jpa.show-sql=true",
|
||||||
|
"spring.jpa.properties.hibernate.format_sql=true",
|
||||||
|
"spring.jpa.generate-ddl=true",
|
||||||
|
"spring.jpa.defer-datasource-initialization=true",
|
||||||
|
"spring.sql.init.data-locations=classpath:product-data.sql"
|
||||||
|
})
|
||||||
|
@Transactional
|
||||||
|
public class ProductRepositoryIntegrationTest {
|
||||||
|
|
||||||
|
private static final String TEXT = "Hand Grip Strengthener";
|
||||||
|
private static final String EXPECTED_HASH_HEX = getSha256Hex(TEXT);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ProductRepository productRepository;
|
||||||
|
|
||||||
|
private static String getSha256Hex(String value) {
|
||||||
|
return Hex.encodeHexString(DigestUtils.sha256(value.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenGetSha256HexByNamedMapping_thenReturnCorrectHash() {
|
||||||
|
var hash = productRepository.getSha256HexByNamedMapping(TEXT);
|
||||||
|
assertThat(hash).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenGetSha256HexByNativeCall_thenReturnCorrectHash() {
|
||||||
|
var hash = productRepository.getSha256HexByNativeCall(TEXT);
|
||||||
|
assertThat(hash).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallGetSha256HexNative_thenReturnCorrectHash() {
|
||||||
|
var hashList = productRepository.getProductNameListInSha256HexByNativeSelect();
|
||||||
|
assertThat(hashList.get(0)).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallGetSha256Hex_thenReturnCorrectHash() {
|
||||||
|
var hashList = productRepository.getProductNameListInSha256Hex();
|
||||||
|
assertThat(hashList.get(0)).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
CREATE ALIAS SHA256_HEX AS '
|
||||||
|
import java.sql.*;
|
||||||
|
@CODE
|
||||||
|
String getSha256Hex(Connection conn, String value) throws SQLException {
|
||||||
|
var sql = "SELECT RAWTOHEX(HASH(''SHA-256'', ?))";
|
||||||
|
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||||
|
stmt.setString(1, value);
|
||||||
|
ResultSet rs = stmt.executeQuery();
|
||||||
|
if (rs.next()) {
|
||||||
|
return rs.getString(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
';
|
||||||
|
|
||||||
|
INSERT INTO product(name) VALUES('Hand Grip Strengthener');
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.boot.connection.via.builder;
|
||||||
|
|
||||||
|
import com.mongodb.ConnectionString;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringMongoConnectionViaBuilderApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaBuilderApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MongoClientSettingsBuilderCustomizer customizer(@Value("${custom.uri}") String uri) {
|
||||||
|
ConnectionString connection = new ConnectionString(uri);
|
||||||
|
return settings -> settings.applyConnectionString(connection);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.boot.connection.via.client;
|
||||||
|
|
||||||
|
import com.mongodb.client.ListDatabasesIterable;
|
||||||
|
import com.mongodb.client.MongoClient;
|
||||||
|
import com.mongodb.client.MongoClients;
|
||||||
|
import org.bson.Document;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||||
|
|
||||||
|
@SpringBootApplication(exclude={EmbeddedMongoAutoConfiguration.class})
|
||||||
|
public class SpringMongoConnectionViaClientApp extends AbstractMongoClientConfiguration {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Value("${spring.data.mongodb.uri}")
|
||||||
|
private String uri;
|
||||||
|
|
||||||
|
@Value("${spring.data.mongodb.database}")
|
||||||
|
private String db;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public MongoClient mongoClient() {
|
||||||
|
MongoClient client = MongoClients.create(uri);
|
||||||
|
ListDatabasesIterable<Document> databases = client.listDatabases();
|
||||||
|
databases.forEach(System.out::println);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getDatabaseName() {
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.boot.connection.via.factory;
|
||||||
|
|
||||||
|
import com.mongodb.ConnectionString;
|
||||||
|
import com.mongodb.client.MongoClient;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringMongoConnectionViaFactoryApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaFactoryApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MongoClientFactoryBean mongo(@Value("${custom.uri}") String uri) throws Exception {
|
||||||
|
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
|
||||||
|
ConnectionString conn = new ConnectionString(uri);
|
||||||
|
mongo.setConnectionString(conn);
|
||||||
|
|
||||||
|
mongo.setSingleton(false);
|
||||||
|
|
||||||
|
MongoClient client = mongo.getObject();
|
||||||
|
client.listDatabaseNames()
|
||||||
|
.forEach(System.out::println);
|
||||||
|
return mongo;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.boot.connection.via.properties;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
|
||||||
|
@PropertySource("classpath:connection.via.properties/application.properties")
|
||||||
|
@SpringBootApplication(exclude={EmbeddedMongoAutoConfiguration.class})
|
||||||
|
public class SpringMongoConnectionViaPropertiesApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplication.run(SpringMongoConnectionViaPropertiesApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
spring.data.mongodb.host=localhost
|
||||||
|
spring.data.mongodb.port=27017
|
||||||
|
spring.data.mongodb.database=baeldung
|
||||||
|
spring.data.mongodb.username=admin
|
||||||
|
spring.data.mongodb.password=password
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.boot.connection.via;
|
||||||
|
|
||||||
|
import com.baeldung.boot.connection.via.client.SpringMongoConnectionViaClientApp;
|
||||||
|
import com.baeldung.boot.connection.via.properties.SpringMongoConnectionViaPropertiesApp;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.BeanCreationException;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class MongoConnectionApplicationLiveTest {
|
||||||
|
private static final String HOST = "localhost";
|
||||||
|
private static final String PORT = "27017";
|
||||||
|
private static final String DB = "baeldung";
|
||||||
|
private static final String USER = "admin";
|
||||||
|
private static final String PASS = "password";
|
||||||
|
|
||||||
|
private void assertInsertSucceeds(ConfigurableApplicationContext context) {
|
||||||
|
String name = "A";
|
||||||
|
|
||||||
|
MongoTemplate mongo = context.getBean(MongoTemplate.class);
|
||||||
|
Document doc = Document.parse("{\"name\":\"" + name + "\"}");
|
||||||
|
Document inserted = mongo.insert(doc, "items");
|
||||||
|
|
||||||
|
assertNotNull(inserted.get("_id"));
|
||||||
|
assertEquals(inserted.get("name"), name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPropertiesConfig_thenInsertSucceeds() {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
|
||||||
|
app.run();
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrecedence_whenSystemConfig_thenInsertSucceeds() {
|
||||||
|
System.setProperty("spring.data.mongodb.host", HOST);
|
||||||
|
System.setProperty("spring.data.mongodb.port", PORT);
|
||||||
|
System.setProperty("spring.data.mongodb.database", DB);
|
||||||
|
System.setProperty("spring.data.mongodb.username", USER);
|
||||||
|
System.setProperty("spring.data.mongodb.password", PASS);
|
||||||
|
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
|
||||||
|
.properties(
|
||||||
|
"spring.data.mongodb.host=oldValue",
|
||||||
|
"spring.data.mongodb.port=oldValue",
|
||||||
|
"spring.data.mongodb.database=oldValue",
|
||||||
|
"spring.data.mongodb.username=oldValue",
|
||||||
|
"spring.data.mongodb.password=oldValue"
|
||||||
|
);
|
||||||
|
app.run();
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConnectionUri_whenAlsoIncludingIndividualParameters_thenInvalidConfig() {
|
||||||
|
System.setProperty(
|
||||||
|
"spring.data.mongodb.uri",
|
||||||
|
"mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
|
||||||
|
);
|
||||||
|
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
|
||||||
|
.properties(
|
||||||
|
"spring.data.mongodb.host=" + HOST,
|
||||||
|
"spring.data.mongodb.port=" + PORT,
|
||||||
|
"spring.data.mongodb.username=" + USER,
|
||||||
|
"spring.data.mongodb.password=" + PASS
|
||||||
|
);
|
||||||
|
|
||||||
|
BeanCreationException e = assertThrows(BeanCreationException.class, () -> {
|
||||||
|
app.run();
|
||||||
|
});
|
||||||
|
|
||||||
|
Throwable rootCause = e.getRootCause();
|
||||||
|
assertTrue(rootCause instanceof IllegalStateException);
|
||||||
|
assertThat(rootCause.getMessage()
|
||||||
|
.contains("Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenClientConfig_thenInsertSucceeds() {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
|
||||||
|
app.web(WebApplicationType.NONE)
|
||||||
|
.run(
|
||||||
|
"--spring.data.mongodb.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB,
|
||||||
|
"--spring.data.mongodb.database=" + DB
|
||||||
|
);
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
}
|
@ -194,7 +194,7 @@
|
|||||||
<lifecycle-mapping.version>1.0.0</lifecycle-mapping.version>
|
<lifecycle-mapping.version>1.0.0</lifecycle-mapping.version>
|
||||||
<sql-maven-plugin.version>1.5</sql-maven-plugin.version>
|
<sql-maven-plugin.version>1.5</sql-maven-plugin.version>
|
||||||
<properties-maven-plugin.version>1.0.0</properties-maven-plugin.version>
|
<properties-maven-plugin.version>1.0.0</properties-maven-plugin.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
<h2.version>2.2.224</h2.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -19,12 +19,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-context</artifactId>
|
<artifactId>spring-context</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-beans</artifactId>
|
<artifactId>spring-beans</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- SpringBoot -->
|
<!-- SpringBoot -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -36,12 +34,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
<version>${h2.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-jdbc</artifactId>
|
<artifactId>spring-jdbc</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mybatis</groupId>
|
<groupId>org.mybatis</groupId>
|
||||||
@ -61,7 +57,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -77,14 +72,10 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Spring -->
|
|
||||||
<org.springframework.version>6.0.13</org.springframework.version>
|
|
||||||
<!-- persistence -->
|
|
||||||
<spring-mybatis.version>3.0.3</spring-mybatis.version>
|
<spring-mybatis.version>3.0.3</spring-mybatis.version>
|
||||||
<mybatis.version>3.5.2</mybatis.version>
|
<mybatis.version>3.5.2</mybatis.version>
|
||||||
<mybatis-spring-boot-starter.version>3.0.3</mybatis-spring-boot-starter.version>
|
<mybatis-spring-boot-starter.version>3.0.3</mybatis-spring-boot-starter.version>
|
||||||
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
|
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
6
pom.xml
6
pom.xml
@ -833,7 +833,7 @@
|
|||||||
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
|
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
|
||||||
<module>spring-jenkins-pipeline</module>
|
<module>spring-jenkins-pipeline</module>
|
||||||
<module>spring-jersey</module>
|
<module>spring-jersey</module>
|
||||||
<module>spring-jinq</module>
|
<!--<module>spring-jinq</module>-->
|
||||||
<module>spring-kafka-2</module>
|
<module>spring-kafka-2</module>
|
||||||
<module>spring-kafka-3</module>
|
<module>spring-kafka-3</module>
|
||||||
<module>spring-kafka</module>
|
<module>spring-kafka</module>
|
||||||
@ -1079,7 +1079,7 @@
|
|||||||
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
|
<!--<module>spring-integration</module>--><!-- failing after upgrading to jdk17-->
|
||||||
<module>spring-jenkins-pipeline</module>
|
<module>spring-jenkins-pipeline</module>
|
||||||
<module>spring-jersey</module>
|
<module>spring-jersey</module>
|
||||||
<module>spring-jinq</module>
|
<!--<module>spring-jinq</module>-->
|
||||||
<module>spring-kafka-2</module>
|
<module>spring-kafka-2</module>
|
||||||
<module>spring-kafka-3</module>
|
<module>spring-kafka-3</module>
|
||||||
<module>spring-kafka</module>
|
<module>spring-kafka</module>
|
||||||
@ -1167,7 +1167,7 @@
|
|||||||
<hamcrest.version>2.2</hamcrest.version>
|
<hamcrest.version>2.2</hamcrest.version>
|
||||||
<hamcrest-all.version>1.3</hamcrest-all.version>
|
<hamcrest-all.version>1.3</hamcrest-all.version>
|
||||||
<mockito.version>4.4.0</mockito.version>
|
<mockito.version>4.4.0</mockito.version>
|
||||||
<byte-buddy.version>1.14.6</byte-buddy.version>
|
<byte-buddy.version>1.14.11</byte-buddy.version>
|
||||||
|
|
||||||
<!-- logging -->
|
<!-- logging -->
|
||||||
<!-- overwriting in the slf4j and logback in the hibernate-jpa, spring-data-eclipselink. When updated to the latest version remove the version from that module-->
|
<!-- overwriting in the slf4j and logback in the hibernate-jpa, spring-data-eclipselink. When updated to the latest version remove the version from that module-->
|
||||||
|
@ -10,9 +10,9 @@ public class GreetingServiceWithoutAOP {
|
|||||||
private static final Logger logger = LoggerFactory.getLogger(GreetingServiceWithoutAOP.class);
|
private static final Logger logger = LoggerFactory.getLogger(GreetingServiceWithoutAOP.class);
|
||||||
|
|
||||||
public String greet(String name) {
|
public String greet(String name) {
|
||||||
logger.info(">> greet() - {}", name);
|
logger.debug(">> greet() - {}", name);
|
||||||
String result = String.format("Hello %s", name);
|
String result = String.format("Hello %s", name);
|
||||||
logger.info("<< greet() - {}", result);
|
logger.debug("<< greet() - {}", result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -28,13 +28,13 @@ public class LoggingAspect {
|
|||||||
public void logBefore(JoinPoint joinPoint) {
|
public void logBefore(JoinPoint joinPoint) {
|
||||||
Object[] args = joinPoint.getArgs();
|
Object[] args = joinPoint.getArgs();
|
||||||
String methodName = joinPoint.getSignature().getName();
|
String methodName = joinPoint.getSignature().getName();
|
||||||
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
|
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterReturning(value = "publicMethodsFromLoggingPackage()", returning = "result")
|
@AfterReturning(value = "publicMethodsFromLoggingPackage()", returning = "result")
|
||||||
public void logAfter(JoinPoint joinPoint, Object result) {
|
public void logAfter(JoinPoint joinPoint, Object result) {
|
||||||
String methodName = joinPoint.getSignature().getName();
|
String methodName = joinPoint.getSignature().getName();
|
||||||
logger.info("<< {}() - {}", methodName, result);
|
logger.debug("<< {}() - {}", methodName, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterThrowing(pointcut = "publicMethodsFromLoggingPackage()", throwing = "exception")
|
@AfterThrowing(pointcut = "publicMethodsFromLoggingPackage()", throwing = "exception")
|
||||||
@ -47,9 +47,9 @@ public class LoggingAspect {
|
|||||||
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
|
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||||
Object[] args = joinPoint.getArgs();
|
Object[] args = joinPoint.getArgs();
|
||||||
String methodName = joinPoint.getSignature().getName();
|
String methodName = joinPoint.getSignature().getName();
|
||||||
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
|
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
|
||||||
Object result = joinPoint.proceed();
|
Object result = joinPoint.proceed();
|
||||||
logger.info("<< {}() - {}", methodName, result);
|
logger.debug("<< {}() - {}", methodName, result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<title>WebJars Demo</title>
|
<title>WebJars Demo</title>
|
||||||
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
|
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Welcome Home</h1>
|
<h1>Welcome Home</h1>
|
||||||
@ -12,8 +12,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
|
<script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
|
||||||
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
|
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
import graphql.schema.Coercing;
|
||||||
|
import graphql.schema.GraphQLScalarType;
|
||||||
|
|
||||||
|
public class GraphQLVoidScalar {
|
||||||
|
|
||||||
|
public static final GraphQLScalarType Void = GraphQLScalarType.newScalar()
|
||||||
|
.name("Void")
|
||||||
|
.description("A custom scalar that represents the null value")
|
||||||
|
.coercing(new Coercing() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object serialize(Object dataFetcherResult) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object parseValue(Object input) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object parseLiteral(Object input) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.build();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.graphql.execution.RuntimeWiringConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class GraphQlConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RuntimeWiringConfigurer runtimeWiringConfigurer() {
|
||||||
|
return wiringBuilder -> wiringBuilder.scalar(GraphQLVoidScalar.Void);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
public class Post {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String title;
|
||||||
|
private String text;
|
||||||
|
private String category;
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTitle() {
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTitle(String title) {
|
||||||
|
this.title = title;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getText() {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setText(String text) {
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCategory() {
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCategory(String category) {
|
||||||
|
this.category = category;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.springframework.graphql.data.method.annotation.Argument;
|
||||||
|
import org.springframework.graphql.data.method.annotation.MutationMapping;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class PostController {
|
||||||
|
|
||||||
|
List<Post> posts = new ArrayList<>();
|
||||||
|
|
||||||
|
@MutationMapping
|
||||||
|
public Void createPostReturnCustomScalar(@Argument String title, @Argument String text, @Argument String category, @Argument String author) {
|
||||||
|
Post post = new Post();
|
||||||
|
post.setId(UUID.randomUUID()
|
||||||
|
.toString());
|
||||||
|
post.setTitle(title);
|
||||||
|
post.setText(text);
|
||||||
|
post.setCategory(category);
|
||||||
|
post.setAuthor(author);
|
||||||
|
posts.add(post);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class ReturnNullApp {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.setProperty("spring.profiles.default", "returnnull");
|
||||||
|
SpringApplication.run(com.baeldung.chooseapi.ChooseApiApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,9 @@
|
|||||||
|
server:
|
||||||
|
port: 8082
|
||||||
|
|
||||||
|
spring:
|
||||||
|
graphql:
|
||||||
|
graphiql:
|
||||||
|
enabled: true
|
||||||
|
schema:
|
||||||
|
locations: classpath:returnnull/
|
@ -0,0 +1,18 @@
|
|||||||
|
scalar Void
|
||||||
|
|
||||||
|
type Mutation {
|
||||||
|
createPostReturnNullableType(title: String!, text: String!, category: String!, author: String!) : Int
|
||||||
|
createPostReturnCustomScalar(title: String!, text: String!, category: String!, author: String!) : Void
|
||||||
|
}
|
||||||
|
|
||||||
|
type Post {
|
||||||
|
id: ID
|
||||||
|
title: String
|
||||||
|
text: String
|
||||||
|
category: String
|
||||||
|
author: String
|
||||||
|
}
|
||||||
|
|
||||||
|
type Query {
|
||||||
|
recentPosts(count: Int, offset: Int): [Post]!
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.returnnull;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.graphql.test.tester.GraphQlTester;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
@GraphQlTest(PostController.class)
|
||||||
|
@ActiveProfiles("returnnull")
|
||||||
|
@Import(GraphQlConfig.class)
|
||||||
|
class PostControllerIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GraphQlTester graphQlTester;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNewPostData_whenExecuteMutation_thenReturnCustomNullScalar() {
|
||||||
|
String documentName = "create_post_return_custom_scalar";
|
||||||
|
|
||||||
|
graphQlTester.documentName(documentName)
|
||||||
|
.variable("title", "New Post")
|
||||||
|
.variable("text", "New post text")
|
||||||
|
.variable("category", "category")
|
||||||
|
.variable("author", "Alex")
|
||||||
|
.execute()
|
||||||
|
.path("createPostReturnCustomScalar")
|
||||||
|
.valueIsNull();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNewPostData_whenExecuteMutation_thenReturnNullType() {
|
||||||
|
String documentName = "create_post_return_nullable_type";
|
||||||
|
|
||||||
|
graphQlTester.documentName(documentName)
|
||||||
|
.variable("title", "New Post")
|
||||||
|
.variable("text", "New post text")
|
||||||
|
.variable("category", "category")
|
||||||
|
.variable("author", "Alex")
|
||||||
|
.execute()
|
||||||
|
.path("createPostReturnNullableType")
|
||||||
|
.valueIsNull();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
mutation createPostReturnCustomScalar($title: String!, $text: String!, $category: String!, $author: String!) {
|
||||||
|
createPostReturnCustomScalar(title: $title, text: $text, category: $category, author: $author)
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
mutation createPostReturnNullableType($title: String!, $text: String!, $category: String!, $author: String!) {
|
||||||
|
createPostReturnNullableType(title: $title, text: $text, category: $category, author: $author)
|
||||||
|
}
|
@ -104,6 +104,13 @@
|
|||||||
<useDefaultDelimiters>false</useDefaultDelimiters>
|
<useDefaultDelimiters>false</useDefaultDelimiters>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<parameters>true</parameters>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
@ -142,12 +149,13 @@
|
|||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud.version>2022.0.4</spring-cloud.version>
|
<spring-cloud.version>2023.0.0</spring-cloud.version>
|
||||||
<commons-configuration.version>1.10</commons-configuration.version>
|
<commons-configuration.version>1.10</commons-configuration.version>
|
||||||
<resource.delimiter>@</resource.delimiter>
|
<resource.delimiter>@</resource.delimiter>
|
||||||
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
|
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
|
||||||
<start-class>com.baeldung.yaml.MyApplication</start-class>
|
<start-class>com.baeldung.yaml.MyApplication</start-class>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
<spring-boot.version>3.2.2</spring-boot.version>
|
||||||
|
<junit-jupiter.version>5.10.2</junit-jupiter.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -53,7 +53,6 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<apache.client5.version>5.0.3</apache.client5.version>
|
<apache.client5.version>5.0.3</apache.client5.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -27,7 +27,7 @@ public class SecureRestTemplateConfig {
|
|||||||
this.sslContext = sslBundle.createSslContext();
|
this.sslContext = sslBundle.createSslContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean(name="secureRestTemplate")
|
||||||
public RestTemplate secureRestTemplate() {
|
public RestTemplate secureRestTemplate() {
|
||||||
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext).build();
|
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext).build();
|
||||||
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
|
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.springbootsslbundles;
|
package com.baeldung.springbootsslbundles;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@ -11,7 +12,7 @@ public class SecureServiceRestApi {
|
|||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public SecureServiceRestApi(RestTemplate restTemplate) {
|
public SecureServiceRestApi(@Qualifier("secureRestTemplate") RestTemplate restTemplate) {
|
||||||
this.restTemplate = restTemplate;
|
this.restTemplate = restTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -9,9 +9,10 @@
|
|||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-boot-modules</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -42,6 +43,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.ehcache</groupId>
|
<groupId>org.ehcache</groupId>
|
||||||
<artifactId>ehcache</artifactId>
|
<artifactId>ehcache</artifactId>
|
||||||
|
<classifier>jakarta</classifier>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
@ -77,8 +79,19 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<skip>true</skip>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<ehcache.version>3.5.2</ehcache.version>
|
|
||||||
<caffeine.version>3.1.8</caffeine.version>
|
<caffeine.version>3.1.8</caffeine.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
@ -10,9 +10,10 @@
|
|||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-modules</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
@ -35,7 +36,7 @@
|
|||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud-dependencies.version>2021.0.3</spring-cloud-dependencies.version>
|
<spring-cloud-dependencies.version>2022.0.3</spring-cloud-dependencies.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.config.server;
|
|||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.Customizer;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@ -10,13 +11,13 @@ public class SecurityConfiguration {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.csrf()
|
http.csrf(csrf -> csrf.ignoringRequestMatchers(
|
||||||
.ignoringAntMatchers("/encrypt/**")
|
"/encrypt/**", "/decrypt/**"
|
||||||
.ignoringAntMatchers("/decrypt/**");
|
))
|
||||||
http.authorizeRequests((requests) -> requests.anyRequest()
|
.authorizeRequests(authz -> authz.anyRequest().authenticated())
|
||||||
.authenticated());
|
.formLogin(Customizer.withDefaults())
|
||||||
http.formLogin();
|
.httpBasic(Customizer.withDefaults());
|
||||||
http.httpBasic();
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Sample Client</description>
|
<description>Spring Cloud Eureka Sample Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Sample Client</description>
|
<description>Spring Cloud Eureka Sample Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka - Feign Client Integration Tests</description>
|
<description>Spring Cloud Eureka - Feign Client Integration Tests</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka - Sample Feign Client</description>
|
<description>Spring Cloud Eureka - Sample Feign Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Server Demo</description>
|
<description>Spring Cloud Eureka Server Demo</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -50,6 +50,18 @@
|
|||||||
<groupId>io.undertow</groupId>
|
<groupId>io.undertow</groupId>
|
||||||
<artifactId>undertow-servlet</artifactId>
|
<artifactId>undertow-servlet</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.wildfly</groupId>
|
||||||
|
<artifactId>wildfly-naming-client</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jboss</groupId>
|
||||||
|
<artifactId>jboss-ejb-client</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.wildfly.common</groupId>
|
||||||
|
<artifactId>wildfly-common</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -21,7 +21,7 @@ public class SpringEjbClientApplication {
|
|||||||
Properties jndiProps = new Properties();
|
Properties jndiProps = new Properties();
|
||||||
jndiProps.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
|
jndiProps.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
|
||||||
jndiProps.put("jboss.naming.client.ejb.context", true);
|
jndiProps.put("jboss.naming.client.ejb.context", true);
|
||||||
jndiProps.put("java.naming.provider.url", "http-remoting://localhost:8080");
|
jndiProps.put("java.naming.provider.url", "remote+http://localhost:8080");
|
||||||
return new InitialContext(jndiProps);
|
return new InitialContext(jndiProps);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ public class SpringEjbClientApplication {
|
|||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
private String getFullName(Class classType) {
|
private String getFullName(Class classType) {
|
||||||
String moduleName = "spring-ejb-remote/";
|
String moduleName = "ejb:/spring-ejb-remote/";
|
||||||
String beanName = classType.getSimpleName();
|
String beanName = classType.getSimpleName();
|
||||||
String viewClassName = classType.getName();
|
String viewClassName = classType.getName();
|
||||||
|
|
||||||
|
@ -38,7 +38,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate.orm</groupId>
|
<groupId>org.hibernate.orm</groupId>
|
||||||
<artifactId>hibernate-core</artifactId>
|
<artifactId>hibernate-core</artifactId>
|
||||||
<version>${hibernate-core.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Testing -->
|
<!-- Testing -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -65,7 +64,6 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<jinq.version>2.0.1</jinq.version>
|
<jinq.version>2.0.1</jinq.version>
|
||||||
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
|
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,4 +1,4 @@
|
|||||||
spring.kafka.bootstrap-servers=localhost:9092,localhost:9093,localhost:9094,localhost:9095
|
spring.kafka.bootstrap-servers=localhost:9092,localhost:9093,localhost:9094
|
||||||
message.topic.name=baeldung
|
message.topic.name=baeldung
|
||||||
long.message.topic.name=longMessage
|
long.message.topic.name=longMessage
|
||||||
greeting.topic.name=greeting
|
greeting.topic.name=greeting
|
||||||
|
@ -26,7 +26,8 @@ import com.baeldung.spring.kafka.dlt.listener.PaymentListenerDltRetryOnError;
|
|||||||
import com.baeldung.spring.kafka.dlt.listener.PaymentListenerNoDlt;
|
import com.baeldung.spring.kafka.dlt.listener.PaymentListenerNoDlt;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
@SpringBootTest(classes = KafkaDltApplication.class)
|
@SpringBootTest(classes = KafkaDltApplication.class,
|
||||||
|
properties = "spring.kafka.bootstrap-servers=localhost:9095")
|
||||||
@EmbeddedKafka(
|
@EmbeddedKafka(
|
||||||
partitions = 1,
|
partitions = 1,
|
||||||
brokerProperties = { "listeners=PLAINTEXT://localhost:9095", "port=9095" },
|
brokerProperties = { "listeners=PLAINTEXT://localhost:9095", "port=9095" },
|
||||||
|
@ -21,7 +21,8 @@ import org.springframework.kafka.test.context.EmbeddedKafka;
|
|||||||
import org.springframework.kafka.test.utils.ContainerTestUtils;
|
import org.springframework.kafka.test.utils.ContainerTestUtils;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
@SpringBootTest(classes = KafkaMultipleTopicsApplication.class)
|
@SpringBootTest(classes = KafkaMultipleTopicsApplication.class,
|
||||||
|
properties = "spring.kafka.bootstrap-servers=localhost:9099")
|
||||||
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" })
|
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" })
|
||||||
@ActiveProfiles("multipletopics")
|
@ActiveProfiles("multipletopics")
|
||||||
public class KafkaMultipleTopicsIntegrationTest {
|
public class KafkaMultipleTopicsIntegrationTest {
|
||||||
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.spring.kafka.kafkaexception;
|
||||||
|
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import javax.management.MBeanServer;
|
||||||
|
import javax.management.ObjectName;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||||
|
import org.apache.kafka.common.serialization.StringSerializer;
|
||||||
|
|
||||||
|
public class HandleInstanceAlreadyExistsException {
|
||||||
|
|
||||||
|
public static void generateUniqueClientIDUsingUUIDRandom() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put("bootstrap.servers", "localhost:9092");
|
||||||
|
props.put("key.serializer", StringSerializer.class);
|
||||||
|
props.put("value.serializer", StringSerializer.class);
|
||||||
|
|
||||||
|
String clientId = "my-producer-" + UUID.randomUUID();
|
||||||
|
props.setProperty("client.id", clientId);
|
||||||
|
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
|
||||||
|
|
||||||
|
clientId = "my-producer-" + UUID.randomUUID();
|
||||||
|
props.setProperty("client.id", clientId);
|
||||||
|
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void closeProducerProperlyBeforeReinstantiate() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put("bootstrap.servers", "localhost:9092");
|
||||||
|
props.put("client.id", "my-producer");
|
||||||
|
props.put("key.serializer", StringSerializer.class);
|
||||||
|
props.put("value.serializer", StringSerializer.class);
|
||||||
|
|
||||||
|
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
|
||||||
|
producer1.close();
|
||||||
|
|
||||||
|
producer1 = new KafkaProducer<>(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void useUniqueObjectName() throws Exception {
|
||||||
|
MBeanServer mBeanServer1 = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
MBeanServer mBeanServer2 = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
|
||||||
|
ObjectName objectName1 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric1");
|
||||||
|
ObjectName objectName2 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric2");
|
||||||
|
|
||||||
|
MyMBean mBean1 = new MyMBean();
|
||||||
|
mBeanServer1.registerMBean(mBean1, objectName1);
|
||||||
|
|
||||||
|
MyMBean mBean2 = new MyMBean();
|
||||||
|
mBeanServer2.registerMBean(mBean2, objectName2);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.spring.kafka.kafkaexception;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class KafkaAppMain {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(KafkaAppMain.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,123 @@
|
|||||||
|
package com.baeldung.spring.kafka.kafkaexception;
|
||||||
|
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.management.Attribute;
|
||||||
|
import javax.management.AttributeList;
|
||||||
|
import javax.management.AttributeNotFoundException;
|
||||||
|
import javax.management.DynamicMBean;
|
||||||
|
import javax.management.InvalidAttributeValueException;
|
||||||
|
import javax.management.MBeanAttributeInfo;
|
||||||
|
import javax.management.MBeanConstructorInfo;
|
||||||
|
import javax.management.MBeanException;
|
||||||
|
import javax.management.MBeanInfo;
|
||||||
|
import javax.management.MBeanNotificationInfo;
|
||||||
|
import javax.management.MBeanOperationInfo;
|
||||||
|
import javax.management.MBeanServer;
|
||||||
|
import javax.management.ObjectName;
|
||||||
|
import javax.management.ReflectionException;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||||
|
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||||
|
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||||
|
import org.apache.kafka.common.serialization.StringSerializer;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class SimulateInstanceAlreadyExistsException {
|
||||||
|
|
||||||
|
public static void jmxRegistrationConflicts() throws Exception {
|
||||||
|
// Create two instances of MBeanServer
|
||||||
|
MBeanServer mBeanServer1 = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
MBeanServer mBeanServer2 = ManagementFactory.getPlatformMBeanServer();
|
||||||
|
|
||||||
|
// Define the same ObjectName for both MBeans
|
||||||
|
ObjectName objectName = new ObjectName("kafka.server:type=KafkaMetrics");
|
||||||
|
|
||||||
|
// Create and register the first MBean
|
||||||
|
MyMBean mBean1 = new MyMBean();
|
||||||
|
mBeanServer1.registerMBean(mBean1, objectName);
|
||||||
|
|
||||||
|
// Attempt to register the second MBean with the same ObjectName
|
||||||
|
MyMBean mBean2 = new MyMBean();
|
||||||
|
mBeanServer2.registerMBean(mBean2, objectName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void duplicateConsumerClientID() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put("bootstrap.servers", "localhost:9092");
|
||||||
|
props.put("client.id", "my-consumer");
|
||||||
|
props.put("group.id", "test-group");
|
||||||
|
props.put("key.deserializer", StringDeserializer.class);
|
||||||
|
props.put("value.deserializer", StringDeserializer.class);
|
||||||
|
|
||||||
|
// Simulating concurrent client creation by multiple threads
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
new Thread(() -> {
|
||||||
|
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void duplicateProducerClientID() throws Exception {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put("bootstrap.servers", "localhost:9092");
|
||||||
|
props.put("client.id", "my-producer");
|
||||||
|
props.put("key.serializer", StringSerializer.class);
|
||||||
|
props.put("value.serializer", StringSerializer.class);
|
||||||
|
|
||||||
|
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
|
||||||
|
// Attempting to create another producer using same client.id
|
||||||
|
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void unclosedProducerAndReinitialize() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put("bootstrap.servers", "localhost:9092");
|
||||||
|
props.put("client.id", "my-producer");
|
||||||
|
props.put("key.serializer", StringSerializer.class);
|
||||||
|
props.put("value.serializer", StringSerializer.class);
|
||||||
|
|
||||||
|
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
|
||||||
|
// Attempting to reinitialize without proper close
|
||||||
|
producer1 = new KafkaProducer<>(props);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyMBean implements DynamicMBean {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AttributeList getAttributes(String[] attributes) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AttributeList setAttributes(AttributeList attributes) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public MBeanInfo getMBeanInfo() {
|
||||||
|
MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
|
||||||
|
MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
|
||||||
|
MBeanOperationInfo[] operations = new MBeanOperationInfo[0];
|
||||||
|
MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];
|
||||||
|
return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications);
|
||||||
|
}
|
||||||
|
}
|
@ -116,7 +116,7 @@ public class KafkaConsumerConfig {
|
|||||||
public ConcurrentKafkaListenerContainerFactory<String, Object> multiTypeKafkaListenerContainerFactory() {
|
public ConcurrentKafkaListenerContainerFactory<String, Object> multiTypeKafkaListenerContainerFactory() {
|
||||||
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
|
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
|
||||||
factory.setConsumerFactory(multiTypeConsumerFactory());
|
factory.setConsumerFactory(multiTypeConsumerFactory());
|
||||||
factory.setRecordMessageConverter(multiTypeConverter());
|
factory.setMessageConverter(multiTypeConverter());
|
||||||
return factory;
|
return factory;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -51,11 +51,14 @@
|
|||||||
<layout>JAR</layout>
|
<layout>JAR</layout>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<parameters>true</parameters>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
10
spring-security-modules/spring-security-oauth2-bff/.gitignore
vendored
Normal file
10
spring-security-modules/spring-security-oauth2-bff/.gitignore
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
**/*.pem
|
||||||
|
**/*.crt
|
||||||
|
**/.env.*
|
||||||
|
**/target/
|
||||||
|
**/build/
|
||||||
|
**/.metadata
|
||||||
|
**/*.project
|
||||||
|
**/*.settings
|
||||||
|
**/*.classpath
|
||||||
|
**/*.factorypath
|
@ -0,0 +1,16 @@
|
|||||||
|
# Editor configuration, see https://editorconfig.org
|
||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.ts]
|
||||||
|
quote_type = single
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
max_line_length = off
|
||||||
|
trim_trailing_whitespace = false
|
42
spring-security-modules/spring-security-oauth2-bff/angular-ui/.gitignore
vendored
Normal file
42
spring-security-modules/spring-security-oauth2-bff/angular-ui/.gitignore
vendored
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
# See http://help.github.com/ignore-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# Compiled output
|
||||||
|
/dist
|
||||||
|
/tmp
|
||||||
|
/out-tsc
|
||||||
|
/bazel-out
|
||||||
|
|
||||||
|
# Node
|
||||||
|
/node_modules
|
||||||
|
npm-debug.log
|
||||||
|
yarn-error.log
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
.idea/
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# Visual Studio Code
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.history/*
|
||||||
|
|
||||||
|
# Miscellaneous
|
||||||
|
/.angular/cache
|
||||||
|
.sass-cache/
|
||||||
|
/connect.lock
|
||||||
|
/coverage
|
||||||
|
/libpeerconnection.log
|
||||||
|
testem.log
|
||||||
|
/typings
|
||||||
|
|
||||||
|
# System files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
@ -0,0 +1,110 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
|
"version": 1,
|
||||||
|
"newProjectRoot": "projects",
|
||||||
|
"projects": {
|
||||||
|
"angular-ui": {
|
||||||
|
"projectType": "application",
|
||||||
|
"schematics": {
|
||||||
|
"@schematics/angular:component": {
|
||||||
|
"style": "scss"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"prefix": "app",
|
||||||
|
"architect": {
|
||||||
|
"build": {
|
||||||
|
"builder": "@angular-devkit/build-angular:application",
|
||||||
|
"options": {
|
||||||
|
"baseHref": "/angular-ui/",
|
||||||
|
"outputPath": "dist/angular-ui",
|
||||||
|
"index": "src/index.html",
|
||||||
|
"browser": "src/main.ts",
|
||||||
|
"polyfills": [
|
||||||
|
"zone.js"
|
||||||
|
],
|
||||||
|
"tsConfig": "tsconfig.app.json",
|
||||||
|
"inlineStyleLanguage": "scss",
|
||||||
|
"assets": [
|
||||||
|
"src/favicon.ico",
|
||||||
|
"src/assets"
|
||||||
|
],
|
||||||
|
"styles": [
|
||||||
|
"src/styles.scss"
|
||||||
|
],
|
||||||
|
"scripts": []
|
||||||
|
},
|
||||||
|
"configurations": {
|
||||||
|
"production": {
|
||||||
|
"budgets": [
|
||||||
|
{
|
||||||
|
"type": "initial",
|
||||||
|
"maximumWarning": "500kb",
|
||||||
|
"maximumError": "1mb"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "anyComponentStyle",
|
||||||
|
"maximumWarning": "2kb",
|
||||||
|
"maximumError": "4kb"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outputHashing": "all"
|
||||||
|
},
|
||||||
|
"development": {
|
||||||
|
"optimization": false,
|
||||||
|
"extractLicenses": false,
|
||||||
|
"sourceMap": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"defaultConfiguration": "production"
|
||||||
|
},
|
||||||
|
"serve": {
|
||||||
|
"builder": "@angular-devkit/build-angular:dev-server",
|
||||||
|
"configurations": {
|
||||||
|
"production": {
|
||||||
|
"buildTarget": "angular-ui:build:production"
|
||||||
|
},
|
||||||
|
"development": {
|
||||||
|
"buildTarget": "angular-ui:build:development"
|
||||||
|
},
|
||||||
|
"local": {
|
||||||
|
"buildTarget": "angular-ui:build:development",
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"port": 4201
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"defaultConfiguration": "development"
|
||||||
|
},
|
||||||
|
"extract-i18n": {
|
||||||
|
"builder": "@angular-devkit/build-angular:extract-i18n",
|
||||||
|
"options": {
|
||||||
|
"buildTarget": "angular-ui:build"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test": {
|
||||||
|
"builder": "@angular-devkit/build-angular:karma",
|
||||||
|
"options": {
|
||||||
|
"polyfills": [
|
||||||
|
"zone.js",
|
||||||
|
"zone.js/testing"
|
||||||
|
],
|
||||||
|
"tsConfig": "tsconfig.spec.json",
|
||||||
|
"inlineStyleLanguage": "scss",
|
||||||
|
"assets": [
|
||||||
|
"src/favicon.ico",
|
||||||
|
"src/assets"
|
||||||
|
],
|
||||||
|
"styles": [
|
||||||
|
"src/styles.scss"
|
||||||
|
],
|
||||||
|
"scripts": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cli": {
|
||||||
|
"analytics": "23e97199-7e93-4604-8730-91fe13971aa4"
|
||||||
|
}
|
||||||
|
}
|
12944
spring-security-modules/spring-security-oauth2-bff/angular-ui/package-lock.json
generated
Normal file
12944
spring-security-modules/spring-security-oauth2-bff/angular-ui/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"name": "angular-ui",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"scripts": {
|
||||||
|
"ng": "ng",
|
||||||
|
"start": "ng serve -c local",
|
||||||
|
"build": "ng build",
|
||||||
|
"watch": "ng build --watch --configuration development",
|
||||||
|
"test": "ng test"
|
||||||
|
},
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@angular/animations": "^17.0.0",
|
||||||
|
"@angular/common": "^17.0.0",
|
||||||
|
"@angular/compiler": "^17.0.0",
|
||||||
|
"@angular/core": "^17.0.0",
|
||||||
|
"@angular/forms": "^17.0.0",
|
||||||
|
"@angular/platform-browser": "^17.0.0",
|
||||||
|
"@angular/platform-browser-dynamic": "^17.0.0",
|
||||||
|
"@angular/router": "^17.0.0",
|
||||||
|
"rxjs": "~7.8.0",
|
||||||
|
"tslib": "^2.3.0",
|
||||||
|
"zone.js": "~0.14.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@angular-devkit/build-angular": "^17.0.10",
|
||||||
|
"@angular/cli": "^17.0.10",
|
||||||
|
"@angular/compiler-cli": "^17.0.0",
|
||||||
|
"@types/jasmine": "~5.1.0",
|
||||||
|
"jasmine-core": "~5.1.0",
|
||||||
|
"karma": "~6.4.0",
|
||||||
|
"karma-chrome-launcher": "~3.2.0",
|
||||||
|
"karma-coverage": "~2.2.0",
|
||||||
|
"karma-jasmine": "~5.1.0",
|
||||||
|
"karma-jasmine-html-reporter": "~2.1.0",
|
||||||
|
"typescript": "~5.2.2"
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { NavigationComponent } from './navigation.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-about',
|
||||||
|
standalone: true,
|
||||||
|
imports: [NavigationComponent],
|
||||||
|
template: `<app-navigation
|
||||||
|
[destination]="['']"
|
||||||
|
label="HOME"
|
||||||
|
></app-navigation>
|
||||||
|
<p>
|
||||||
|
This application is a show-case for an Angular app consuming a REST API
|
||||||
|
through an OAuth2 BFF.
|
||||||
|
</p>`,
|
||||||
|
styles: ``,
|
||||||
|
})
|
||||||
|
export class AboutView {}
|
@ -0,0 +1,27 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { HttpClientModule } from '@angular/common/http';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { RouterOutlet } from '@angular/router';
|
||||||
|
import { AuthenticationComponent } from './auth/authentication.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-root',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
RouterOutlet,
|
||||||
|
HttpClientModule,
|
||||||
|
AuthenticationComponent,
|
||||||
|
],
|
||||||
|
template: `<div style="display: flex;">
|
||||||
|
<div style="margin: auto;"></div>
|
||||||
|
<h1>Angular UI</h1>
|
||||||
|
<div style="margin: auto;"></div>
|
||||||
|
<app-authentication style="margin: auto 1em;"></app-authentication>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<router-outlet></router-outlet>
|
||||||
|
</div>`,
|
||||||
|
styles: [],
|
||||||
|
})
|
||||||
|
export class AppComponent {}
|
@ -0,0 +1,12 @@
|
|||||||
|
import { ApplicationConfig } from '@angular/core';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { routes } from './app.routes';
|
||||||
|
|
||||||
|
export const appConfig: ApplicationConfig = {
|
||||||
|
providers: [provideRouter(routes), provideHttpClient()],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const reverseProxyUri = 'http://localhost:7080';
|
||||||
|
export const baseUri = `${reverseProxyUri}/angular-ui/`;
|
@ -0,0 +1,9 @@
|
|||||||
|
import { Routes } from '@angular/router';
|
||||||
|
import { AboutView } from './about.view';
|
||||||
|
import { HomeView } from './home.view';
|
||||||
|
|
||||||
|
export const routes: Routes = [
|
||||||
|
{ path: '', component: HomeView },
|
||||||
|
{ path: 'about', component: AboutView },
|
||||||
|
{ path: '**', redirectTo: '/' },
|
||||||
|
];
|
@ -0,0 +1,27 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { baseUri, reverseProxyUri } from '../app.config';
|
||||||
|
import { UserService } from './user.service';
|
||||||
|
import { LoginComponent } from './login.component';
|
||||||
|
import { LogoutComponent } from './logout.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-authentication',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, ReactiveFormsModule, LoginComponent, LogoutComponent],
|
||||||
|
template: `<span>
|
||||||
|
<app-login *ngIf="!isAuthenticated"></app-login>
|
||||||
|
<app-logout *ngIf="isAuthenticated"></app-logout>
|
||||||
|
</span>`,
|
||||||
|
styles: ``,
|
||||||
|
})
|
||||||
|
export class AuthenticationComponent {
|
||||||
|
constructor(private user: UserService) {}
|
||||||
|
|
||||||
|
get isAuthenticated(): boolean {
|
||||||
|
return this.user.current.isAuthenticated;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,152 @@
|
|||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
|
||||||
|
import { Observable, map } from 'rxjs';
|
||||||
|
import { UserService } from './user.service';
|
||||||
|
import { baseUri } from '../app.config';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
|
||||||
|
enum LoginExperience {
|
||||||
|
IFRAME,
|
||||||
|
DEFAULT,
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LoginOptionDto {
|
||||||
|
label: string;
|
||||||
|
loginUri: string;
|
||||||
|
isSameAuthority: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loginOptions(http: HttpClient): Observable<Array<LoginOptionDto>> {
|
||||||
|
return http
|
||||||
|
.get('/bff/login-options')
|
||||||
|
.pipe(map((dto: any) => dto as LoginOptionDto[]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-login',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, ReactiveFormsModule],
|
||||||
|
template: `<span>
|
||||||
|
<select *ngIf="loginExperiences.length > 1" [formControl]="selectedLoginExperience">
|
||||||
|
<option *ngFor="let le of loginExperiences">
|
||||||
|
{{ loginExperienceLabel(le) }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<button (click)="login()" [disabled]="!isLoginEnabled">Login</button>
|
||||||
|
</span>
|
||||||
|
<div
|
||||||
|
class="modal-overlay"
|
||||||
|
*ngIf="isLoginModalDisplayed && !isAuthenticated"
|
||||||
|
(click)="isLoginModalDisplayed = false"
|
||||||
|
>
|
||||||
|
<div class="modal">
|
||||||
|
<iframe
|
||||||
|
[src]="iframeSrc"
|
||||||
|
frameborder="0"
|
||||||
|
(load)="onIframeLoad($event)"
|
||||||
|
></iframe>
|
||||||
|
<button class="close-button" (click)="isLoginModalDisplayed = false">
|
||||||
|
Discard
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>`,
|
||||||
|
styles: `.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
background-color: rgba(0, 0, 0, 0.5);
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
z-index: 9999;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal {
|
||||||
|
background-color: #fff;
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 5px;
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 800px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal iframe {
|
||||||
|
width: 100%;
|
||||||
|
height: 600px;
|
||||||
|
border: none;
|
||||||
|
}`,
|
||||||
|
})
|
||||||
|
export class LoginComponent {
|
||||||
|
isLoginModalDisplayed = false;
|
||||||
|
iframeSrc?: SafeUrl;
|
||||||
|
loginExperiences: LoginExperience[] = [];
|
||||||
|
selectedLoginExperience = new FormControl<LoginExperience | null>(null, [
|
||||||
|
Validators.required,
|
||||||
|
]);
|
||||||
|
|
||||||
|
private loginUri?: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
http: HttpClient,
|
||||||
|
private user: UserService,
|
||||||
|
private router: Router,
|
||||||
|
private sanitizer: DomSanitizer
|
||||||
|
) {
|
||||||
|
loginOptions(http).subscribe((opts) => {
|
||||||
|
if (opts.length) {
|
||||||
|
this.loginUri = opts[0].loginUri;
|
||||||
|
if (opts[0].isSameAuthority) {
|
||||||
|
this.loginExperiences.push(LoginExperience.IFRAME);
|
||||||
|
}
|
||||||
|
this.loginExperiences.push(LoginExperience.DEFAULT);
|
||||||
|
this.selectedLoginExperience.patchValue(this.loginExperiences[0]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get isLoginEnabled(): boolean {
|
||||||
|
return (
|
||||||
|
this.selectedLoginExperience.valid && !this.user.current.isAuthenticated
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
get isAuthenticated(): boolean {
|
||||||
|
return this.user.current.isAuthenticated;
|
||||||
|
}
|
||||||
|
|
||||||
|
login() {
|
||||||
|
if (!this.loginUri) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(this.loginUri);
|
||||||
|
url.searchParams.append(
|
||||||
|
'post_login_success_uri',
|
||||||
|
`${baseUri}${this.router.url}`
|
||||||
|
);
|
||||||
|
const loginUrl = url.toString();
|
||||||
|
|
||||||
|
if (this.selectedLoginExperience.value === LoginExperience.IFRAME) {
|
||||||
|
this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(loginUrl);
|
||||||
|
this.isLoginModalDisplayed = true;
|
||||||
|
} else {
|
||||||
|
window.location.href = loginUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onIframeLoad(event: any) {
|
||||||
|
if (!!event.currentTarget.src) {
|
||||||
|
this.user.refresh();
|
||||||
|
this.isLoginModalDisplayed = !this.user.current.isAuthenticated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loginExperienceLabel(le: LoginExperience) {
|
||||||
|
return LoginExperience[le].toLowerCase()
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,39 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { UserService } from './user.service';
|
||||||
|
import { lastValueFrom } from 'rxjs';
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { baseUri } from '../app.config';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-logout',
|
||||||
|
standalone: true,
|
||||||
|
imports: [],
|
||||||
|
template: `
|
||||||
|
<button (click)="logout()">Logout</button>
|
||||||
|
`,
|
||||||
|
styles: ``
|
||||||
|
})
|
||||||
|
export class LogoutComponent {
|
||||||
|
|
||||||
|
constructor(private http: HttpClient, private user: UserService) {}
|
||||||
|
|
||||||
|
logout() {
|
||||||
|
lastValueFrom(
|
||||||
|
this.http.post('/bff/logout', null, {
|
||||||
|
headers: {
|
||||||
|
'X-POST-LOGOUT-SUCCESS-URI': baseUri,
|
||||||
|
},
|
||||||
|
observe: 'response',
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.then((resp) => {
|
||||||
|
const logoutUri = resp.headers.get('Location');
|
||||||
|
if (!!logoutUri) {
|
||||||
|
window.location.href = logoutUri;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.user.refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,88 @@
|
|||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { BehaviorSubject, Observable, Subscription, interval } from 'rxjs';
|
||||||
|
|
||||||
|
interface UserinfoDto {
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
roles: string[];
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class User {
|
||||||
|
static readonly ANONYMOUS = new User('', '', []);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly name: string,
|
||||||
|
readonly email: string,
|
||||||
|
readonly roles: string[]
|
||||||
|
) {}
|
||||||
|
|
||||||
|
get isAuthenticated(): boolean {
|
||||||
|
return !!this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasAnyRole(...roles: string[]): boolean {
|
||||||
|
for (const r of roles) {
|
||||||
|
if (this.roles.includes(r)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class UserService {
|
||||||
|
private user$ = new BehaviorSubject<User>(User.ANONYMOUS);
|
||||||
|
private refreshSub?: Subscription;
|
||||||
|
|
||||||
|
constructor(private http: HttpClient) {
|
||||||
|
this.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh(): void {
|
||||||
|
this.refreshSub?.unsubscribe();
|
||||||
|
this.http.get('/bff/api/me').subscribe({
|
||||||
|
next: (dto: any) => {
|
||||||
|
const user = dto as UserinfoDto;
|
||||||
|
if (
|
||||||
|
user.username !== this.user$.value.name ||
|
||||||
|
user.email !== this.user$.value.email ||
|
||||||
|
(user.roles || []).toString() !== this.user$.value.roles.toString()
|
||||||
|
) {
|
||||||
|
this.user$.next(
|
||||||
|
user.username
|
||||||
|
? new User(
|
||||||
|
user.username || '',
|
||||||
|
user.email || '',
|
||||||
|
user.roles || []
|
||||||
|
)
|
||||||
|
: User.ANONYMOUS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!!user.exp) {
|
||||||
|
const now = Date.now();
|
||||||
|
const delay = (1000 * user.exp - now) * 0.8;
|
||||||
|
if (delay > 2000) {
|
||||||
|
this.refreshSub = interval(delay).subscribe(() => this.refresh());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: (error) => {
|
||||||
|
console.warn(error);
|
||||||
|
this.user$.next(User.ANONYMOUS);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get valueChanges(): Observable<User> {
|
||||||
|
return this.user$;
|
||||||
|
}
|
||||||
|
|
||||||
|
get current(): User {
|
||||||
|
return this.user$.value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { Subscription } from 'rxjs';
|
||||||
|
import { NavigationComponent } from './navigation.component';
|
||||||
|
import { User, UserService } from './auth/user.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-home',
|
||||||
|
standalone: true,
|
||||||
|
imports: [NavigationComponent],
|
||||||
|
template: `<app-navigation
|
||||||
|
[destination]="['about']"
|
||||||
|
label="About"
|
||||||
|
></app-navigation>
|
||||||
|
<p>{{ message }}</p>`,
|
||||||
|
styles: [],
|
||||||
|
})
|
||||||
|
export class HomeView {
|
||||||
|
message = '';
|
||||||
|
|
||||||
|
private userSubscription?: Subscription;
|
||||||
|
|
||||||
|
constructor(user: UserService) {
|
||||||
|
this.userSubscription = user.valueChanges.subscribe((u) => {
|
||||||
|
this.message = u.isAuthenticated
|
||||||
|
? `Hi ${u.name}, you are granted with ${HomeView.rolesStr(u)}.`
|
||||||
|
: 'You are not authenticated.';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static rolesStr(user: User) {
|
||||||
|
if(!user?.roles?.length) {
|
||||||
|
return '[]'
|
||||||
|
}
|
||||||
|
return `["${user.roles.join('", "')}"]`
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.userSubscription?.unsubscribe();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
import { Component, Input } from '@angular/core';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { Subscription } from 'rxjs';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-navigation',
|
||||||
|
standalone: true,
|
||||||
|
imports: [],
|
||||||
|
template: `<button (click)="navigate()">{{ label }}</button>`,
|
||||||
|
styles: ``,
|
||||||
|
})
|
||||||
|
export class NavigationComponent {
|
||||||
|
@Input()
|
||||||
|
label!: string;
|
||||||
|
|
||||||
|
@Input()
|
||||||
|
destination!: string[];
|
||||||
|
|
||||||
|
private userSubscription?: Subscription;
|
||||||
|
|
||||||
|
constructor(private router: Router) {}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
this.userSubscription?.unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
navigate() {
|
||||||
|
this.router.navigate(this.destination);
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
After Width: | Height: | Size: 15 KiB |
@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>AngularUi</title>
|
||||||
|
<base href="/">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<app-root></app-root>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -0,0 +1,6 @@
|
|||||||
|
import { bootstrapApplication } from '@angular/platform-browser';
|
||||||
|
import { appConfig } from './app/app.config';
|
||||||
|
import { AppComponent } from './app/app.component';
|
||||||
|
|
||||||
|
bootstrapApplication(AppComponent, appConfig)
|
||||||
|
.catch((err) => console.error(err));
|
@ -0,0 +1 @@
|
|||||||
|
/* You can add global styles to this file, and also import other style files */
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user