Merge branch 'eugenp:master' into master
This commit is contained in:
commit
df9944e4be
@ -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">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.apache.camel.impl.engine" level="WARN"/>
|
||||
</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
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import groovy.io.FileType
|
||||
import groovy.io.FileVisitResult
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class TraverseFileTreeUnitTest {
|
||||
@Test
|
||||
void whenUsingEachFile_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException)
|
||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||
var files = []
|
||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileMatch_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachDirRecurse { dir ->
|
||||
println "$dir.parent $dir.name"
|
||||
files.add("$dir.parent $dir.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||
var files = []
|
||||
new File('src/main').traverse { file ->
|
||||
if (file.directory && file.name == 'groovy') {
|
||||
FileVisitResult.SKIP_SUBTREE
|
||||
} 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 static org.junit.Assert.assertFalse
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@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");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
// System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
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");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
// System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
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();
|
||||
while (it.hasNext()) {
|
||||
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>
|
@ -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()))) {
|
||||
String line;
|
||||
logger.info("Response from " + url + ":");
|
||||
logger.debug("Response from " + url + ":");
|
||||
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
|
||||
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||
|
@ -8,9 +8,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<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>
|
||||
<version>${google-protobuf.version}</version>
|
||||
</dependency>
|
||||
<!-- jetcd core api -->
|
||||
<dependency>
|
||||
<groupId>io.etcd</groupId>
|
||||
<artifactId>jetcd-core</artifactId>
|
||||
<version>${jetcd-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@ -110,6 +116,7 @@
|
||||
<yamlbeans.version>1.15</yamlbeans.version>
|
||||
<apache-thrift.version>0.14.2</apache-thrift.version>
|
||||
<google-protobuf.version>3.17.3</google-protobuf.version>
|
||||
<jetcd-version>0.7.7</jetcd-version>
|
||||
</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();
|
||||
}
|
||||
}
|
||||
}
|
@ -62,6 +62,11 @@
|
||||
<artifactId>modelmapper</artifactId>
|
||||
<version>${modelmapper.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
@ -88,6 +93,7 @@
|
||||
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<modelmapper.version>3.2.0</modelmapper.version>
|
||||
<commons-codec.version>1.16.1</commons-codec.version>
|
||||
<lombok.version>1.18.30</lombok.version>
|
||||
</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>
|
||||
<sql-maven-plugin.version>1.5</sql-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>
|
||||
|
||||
</project>
|
@ -19,12 +19,10 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<!-- SpringBoot -->
|
||||
<dependency>
|
||||
@ -36,12 +34,10 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-jdbc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mybatis</groupId>
|
||||
@ -61,7 +57,6 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -77,14 +72,10 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>6.0.13</org.springframework.version>
|
||||
<!-- persistence -->
|
||||
<spring-mybatis.version>3.0.3</spring-mybatis.version>
|
||||
<mybatis.version>3.5.2</mybatis.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.version>3.1.5</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
2
pom.xml
2
pom.xml
@ -1167,7 +1167,7 @@
|
||||
<hamcrest.version>2.2</hamcrest.version>
|
||||
<hamcrest-all.version>1.3</hamcrest-all.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 -->
|
||||
<!-- 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);
|
||||
|
||||
public String greet(String name) {
|
||||
logger.info(">> greet() - {}", name);
|
||||
logger.debug(">> greet() - {}", name);
|
||||
String result = String.format("Hello %s", name);
|
||||
logger.info("<< greet() - {}", result);
|
||||
logger.debug("<< greet() - {}", result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -28,13 +28,13 @@ public class LoggingAspect {
|
||||
public void logBefore(JoinPoint joinPoint) {
|
||||
Object[] args = joinPoint.getArgs();
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
|
||||
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
|
||||
}
|
||||
|
||||
@AfterReturning(value = "publicMethodsFromLoggingPackage()", returning = "result")
|
||||
public void logAfter(JoinPoint joinPoint, Object result) {
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
logger.info("<< {}() - {}", methodName, result);
|
||||
logger.debug("<< {}() - {}", methodName, result);
|
||||
}
|
||||
|
||||
@AfterThrowing(pointcut = "publicMethodsFromLoggingPackage()", throwing = "exception")
|
||||
@ -47,9 +47,9 @@ public class LoggingAspect {
|
||||
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
Object[] args = joinPoint.getArgs();
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
|
||||
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
|
||||
Object result = joinPoint.proceed();
|
||||
logger.info("<< {}() - {}", methodName, result);
|
||||
logger.debug("<< {}() - {}", methodName, result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
<html>
|
||||
<head>
|
||||
<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>
|
||||
<body>
|
||||
<h1>Welcome Home</h1>
|
||||
@ -12,8 +12,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script 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/jquery/3.1.1/jquery.min.js}"></script>
|
||||
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
|
||||
|
||||
</body>
|
||||
</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>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@ -142,12 +149,11 @@
|
||||
</profiles>
|
||||
|
||||
<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>
|
||||
<resource.delimiter>@</resource.delimiter>
|
||||
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
|
||||
<start-class>com.baeldung.yaml.MyApplication</start-class>
|
||||
<spring-boot.version>3.1.5</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -53,7 +53,6 @@
|
||||
|
||||
<properties>
|
||||
<apache.client5.version>5.0.3</apache.client5.version>
|
||||
<spring-boot.version>3.1.5</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -27,7 +27,7 @@ public class SecureRestTemplateConfig {
|
||||
this.sslContext = sslBundle.createSslContext();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Bean(name="secureRestTemplate")
|
||||
public RestTemplate secureRestTemplate() {
|
||||
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext).build();
|
||||
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.baeldung.springbootsslbundles;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
@ -11,7 +12,7 @@ public class SecureServiceRestApi {
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
public SecureServiceRestApi(RestTemplate restTemplate) {
|
||||
public SecureServiceRestApi(@Qualifier("secureRestTemplate") RestTemplate restTemplate) {
|
||||
this.restTemplate = restTemplate;
|
||||
}
|
||||
|
||||
|
@ -9,9 +9,10 @@
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@ -42,6 +43,7 @@
|
||||
<dependency>
|
||||
<groupId>org.ehcache</groupId>
|
||||
<artifactId>ehcache</artifactId>
|
||||
<classifier>jakarta</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
@ -77,8 +79,19 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<ehcache.version>3.5.2</ehcache.version>
|
||||
<caffeine.version>3.1.8</caffeine.version>
|
||||
</properties>
|
||||
|
||||
|
@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.UUID;
|
||||
|
@ -10,9 +10,10 @@
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<artifactId>spring-cloud-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
@ -35,7 +36,7 @@
|
||||
</dependencyManagement>
|
||||
|
||||
<properties>
|
||||
<spring-cloud-dependencies.version>2021.0.3</spring-cloud-dependencies.version>
|
||||
<spring-cloud-dependencies.version>2022.0.3</spring-cloud-dependencies.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.config.server;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
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.web.SecurityFilterChain;
|
||||
|
||||
@ -10,13 +11,13 @@ public class SecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.ignoringAntMatchers("/encrypt/**")
|
||||
.ignoringAntMatchers("/decrypt/**");
|
||||
http.authorizeRequests((requests) -> requests.anyRequest()
|
||||
.authenticated());
|
||||
http.formLogin();
|
||||
http.httpBasic();
|
||||
http.csrf(csrf -> csrf.ignoringRequestMatchers(
|
||||
"/encrypt/**", "/decrypt/**"
|
||||
))
|
||||
.authorizeRequests(authz -> authz.anyRequest().authenticated())
|
||||
.formLogin(Customizer.withDefaults())
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
|
@ -10,7 +10,7 @@
|
||||
<description>Spring Cloud Eureka Sample Client</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-eureka</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -10,7 +10,7 @@
|
||||
<description>Spring Cloud Eureka Sample Client</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-eureka</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -10,7 +10,7 @@
|
||||
<description>Spring Cloud Eureka - Feign Client Integration Tests</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-eureka</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -10,7 +10,7 @@
|
||||
<description>Spring Cloud Eureka - Sample Feign Client</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-eureka</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -10,7 +10,7 @@
|
||||
<description>Spring Cloud Eureka Server Demo</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-cloud-eureka</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
@ -50,6 +50,18 @@
|
||||
<groupId>io.undertow</groupId>
|
||||
<artifactId>undertow-servlet</artifactId>
|
||||
</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>
|
||||
|
||||
<build>
|
||||
|
@ -21,7 +21,7 @@ public class SpringEjbClientApplication {
|
||||
Properties jndiProps = new Properties();
|
||||
jndiProps.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
|
||||
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);
|
||||
}
|
||||
|
||||
@ -37,7 +37,7 @@ public class SpringEjbClientApplication {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private String getFullName(Class classType) {
|
||||
String moduleName = "spring-ejb-remote/";
|
||||
String moduleName = "ejb:/spring-ejb-remote/";
|
||||
String beanName = classType.getSimpleName();
|
||||
String viewClassName = classType.getName();
|
||||
|
||||
|
@ -38,7 +38,6 @@
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate-core.version}</version>
|
||||
</dependency>
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
@ -65,7 +64,6 @@
|
||||
<properties>
|
||||
<jinq.version>2.0.1</jinq.version>
|
||||
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
|
||||
<spring-boot.version>3.1.5</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</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
|
||||
long.message.topic.name=longMessage
|
||||
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 org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
@SpringBootTest(classes = KafkaDltApplication.class)
|
||||
@SpringBootTest(classes = KafkaDltApplication.class,
|
||||
properties = "spring.kafka.bootstrap-servers=localhost:9095")
|
||||
@EmbeddedKafka(
|
||||
partitions = 1,
|
||||
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.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" })
|
||||
@ActiveProfiles("multipletopics")
|
||||
public class KafkaMultipleTopicsIntegrationTest {
|
||||
|
@ -51,11 +51,14 @@
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>3.1.5</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -10,8 +10,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-modules</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@ -29,7 +30,7 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
@ -56,4 +57,7 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<start-class>com.baeldung.manuallogout.ManualLogoutApplication</start-class>
|
||||
</properties>
|
||||
</project>
|
@ -1,20 +1,20 @@
|
||||
package com.baeldung.logoutredirects.securityconfig;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SpringSecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests(authz -> authz.mvcMatchers("/login")
|
||||
http.authorizeHttpRequests(authz -> authz.requestMatchers("/login")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
|
@ -5,9 +5,6 @@ import static org.springframework.security.web.header.writers.ClearSiteDataHeade
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.Cookie;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@ -20,11 +17,14 @@ import org.springframework.security.web.authentication.logout.HeaderWriterLogout
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SimpleSecurityConfiguration {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class);
|
||||
|
||||
@Order(4)
|
||||
@Configuration
|
||||
@ -32,8 +32,8 @@ public class SimpleSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChainLogoutOnRequest(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/request/**")
|
||||
.authorizeRequests(authz -> authz.anyRequest()
|
||||
http.securityMatcher("/request/**")
|
||||
.authorizeHttpRequests(authz -> authz.anyRequest()
|
||||
.permitAll())
|
||||
.logout(logout -> logout.logoutUrl("/request/logout")
|
||||
.addLogoutHandler((request, response, auth) -> {
|
||||
@ -53,8 +53,8 @@ public class SimpleSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChainDefaultLogout(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/basic/**")
|
||||
.authorizeRequests(authz -> authz.anyRequest()
|
||||
http.securityMatcher("/basic/**")
|
||||
.authorizeHttpRequests(authz -> authz.anyRequest()
|
||||
.permitAll())
|
||||
.logout(logout -> logout.logoutUrl("/basic/basiclogout"));
|
||||
return http.build();
|
||||
@ -67,8 +67,8 @@ public class SimpleSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/cookies/**")
|
||||
.authorizeRequests(authz -> authz.anyRequest()
|
||||
http.securityMatcher("/cookies/**")
|
||||
.authorizeHttpRequests(authz -> authz.anyRequest()
|
||||
.permitAll())
|
||||
.logout(logout -> logout.logoutUrl("/cookies/cookielogout")
|
||||
.addLogoutHandler(new SecurityContextLogoutHandler())
|
||||
@ -92,8 +92,8 @@ public class SimpleSecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/csd/**")
|
||||
.authorizeRequests(authz -> authz.anyRequest()
|
||||
http.securityMatcher("/csd/**")
|
||||
.authorizeHttpRequests(authz -> authz.anyRequest()
|
||||
.permitAll())
|
||||
.logout(logout -> logout.logoutUrl("/csd/csdlogout")
|
||||
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE))));
|
||||
|
@ -9,9 +9,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@ -22,6 +19,9 @@ import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(SimpleSecurityConfiguration.class)
|
||||
public class ManualLogoutIntegrationTest {
|
||||
|
@ -10,9 +10,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<artifactId>parent-spring-6</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-spring-5</relativePath>
|
||||
<relativePath>../../parent-spring-6</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@ -20,17 +20,17 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${spring-security.version}</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${spring-security.version}</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
<version>${spring-security.version}</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
@ -65,22 +65,21 @@
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>${jakarta-servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<scope>runtime</scope>
|
||||
<groupId>jakarta.servlet.jsp.jstl</groupId>
|
||||
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
|
||||
<version>${jakarta-servlet-jsp.version}</version>
|
||||
</dependency>
|
||||
<!-- Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring-boot-starter-test.version}</version>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -153,6 +152,8 @@
|
||||
<!-- frontend -->
|
||||
<node.version>v8.11.3</node.version>
|
||||
<npm.version>6.1.0</npm.version>
|
||||
<jakarta-servlet-jsp.version>3.0.0</jakarta-servlet-jsp.version>
|
||||
<jakarta-servlet-api.version>6.1.0-M1</jakarta-servlet-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,5 +1,4 @@
|
||||
package com.baeldung.spring;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -10,6 +9,8 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/rest")
|
||||
public class RestController {
|
||||
|
@ -38,28 +38,21 @@ public class SecSecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/admin/**")
|
||||
.hasRole("ADMIN")
|
||||
.antMatchers("/anonymous*")
|
||||
.anonymous()
|
||||
.antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/index.html")
|
||||
.loginProcessingUrl("/perform_login")
|
||||
.defaultSuccessUrl("/homepage.html", true)
|
||||
.failureUrl("/index.html?error=true")
|
||||
.and()
|
||||
.logout()
|
||||
.logoutUrl("/perform_logout")
|
||||
.deleteCookies("JSESSIONID");
|
||||
return http.build();
|
||||
return http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
|
||||
.authorizeHttpRequests(request -> request.requestMatchers("/admin/**")
|
||||
.hasRole("ADMIN")
|
||||
.requestMatchers("/anonymous*")
|
||||
.anonymous()
|
||||
.requestMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.formLogin(form -> form.loginPage("/index.html")
|
||||
.loginProcessingUrl("/perform_login")
|
||||
.defaultSuccessUrl("/homepage.html", true)
|
||||
.failureUrl("/index.html?error=true"))
|
||||
.logout(logout -> logout.logoutUrl("/perform_logout")
|
||||
.deleteCookies("JSESSIONID"))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
@ -1,19 +1,22 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.spring.MvcConfig;
|
||||
import com.baeldung.spring.SecSecurityConfig;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class })
|
||||
public class SpringContextTest {
|
||||
@ExtendWith(SpringExtension.class)
|
||||
class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -10,8 +10,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-modules</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@ -26,11 +27,11 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring5</artifactId>
|
||||
<artifactId>thymeleaf-spring6</artifactId>
|
||||
</dependency>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
@ -85,23 +86,24 @@
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<groupId>jakarta.servlet.jsp.jstl</groupId>
|
||||
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- http -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcore</artifactId>
|
||||
<groupId>org.apache.httpcomponents.core5</groupId>
|
||||
<artifactId>httpcore5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5</artifactId>
|
||||
</dependency>
|
||||
<!-- util -->
|
||||
<dependency>
|
||||
|
@ -2,36 +2,28 @@ package com.baeldung.config;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.FilterRegistration.Dynamic;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
import jakarta.servlet.FilterRegistration.Dynamic;
|
||||
import jakarta.servlet.ServletContext;
|
||||
import jakarta.servlet.ServletRegistration;
|
||||
|
||||
public class MainWebAppInitializer implements WebApplicationInitializer {
|
||||
|
||||
public MainWebAppInitializer() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
/**
|
||||
* Register and configure all Servlet container components necessary to power the web application.
|
||||
*/
|
||||
@Override
|
||||
public void onStartup(final ServletContext sc) throws ServletException {
|
||||
public void onStartup(final ServletContext sc) {
|
||||
System.out.println("MyWebAppInitializer.onStartup()");
|
||||
|
||||
// Create the 'root' Spring application context
|
||||
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
||||
root.scan("com.baeldung.config.parent");
|
||||
// root.getEnvironment().setDefaultProfiles("embedded");
|
||||
|
||||
// Manages the lifecycle of the root application context
|
||||
sc.addListener(new ContextLoaderListener(root));
|
||||
|
@ -8,15 +8,14 @@ import org.springframework.security.access.intercept.RunAsManager;
|
||||
import org.springframework.security.access.intercept.RunAsManagerImpl;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
@EnableMethodSecurity(securedEnabled = true)
|
||||
public class MethodSecurityConfig {
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
protected RunAsManager runAsManager() {
|
||||
RunAsManagerImpl runAsManager = new RunAsManagerImpl();
|
||||
runAsManager.setKey("MyRunAsKey");
|
||||
@ -24,7 +23,7 @@ public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) {
|
||||
auth.authenticationProvider(runAsAuthenticationProvider());
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,6 @@ package com.baeldung.config.child;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
@ -13,37 +12,31 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
|
||||
import org.thymeleaf.spring5.ISpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
|
||||
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.extras.springsecurity6.dialect.SpringSecurityDialect;
|
||||
import org.thymeleaf.spring6.ISpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
|
||||
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ITemplateResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan("com.baeldung.web")
|
||||
//@ImportResource({ "classpath:prop.xml" })
|
||||
//@PropertySource("classpath:foo.properties")
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
public WebConfig() {
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public WebConfig(ApplicationContext applicationContext) {
|
||||
super();
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Override
|
||||
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new MappingJackson2HttpMessageConverter());
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
|
||||
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
|
||||
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.config.parent;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
@ -18,8 +18,11 @@ import com.baeldung.security.CustomAuthenticationProvider;
|
||||
@ComponentScan("com.baeldung.security")
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private CustomAuthenticationProvider authProvider;
|
||||
private final CustomAuthenticationProvider authProvider;
|
||||
|
||||
public SecurityConfig(CustomAuthenticationProvider authProvider) {
|
||||
this.authProvider = authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
|
||||
@ -30,12 +33,9 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.httpBasic();
|
||||
return http.build();
|
||||
return http.authorizeHttpRequests(request -> request.anyRequest()
|
||||
.authenticated())
|
||||
.httpBasic(Customizer.withDefaults())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -12,12 +12,6 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
@PropertySource("classpath:foo.properties")
|
||||
public class ServiceConfig {
|
||||
|
||||
public ServiceConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
|
||||
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
|
||||
|
@ -11,8 +11,6 @@ public class AuthenticationFacade implements IAuthenticationFacade {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public final Authentication getAuthentication() {
|
||||
return SecurityContextHolder.getContext().getAuthentication();
|
||||
|
@ -20,21 +20,21 @@ public class CustomAuthenticationProvider implements AuthenticationProvider {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
|
||||
final String name = authentication.getName();
|
||||
final String password = authentication.getCredentials().toString();
|
||||
if (name.equals("admin") && password.equals("system")) {
|
||||
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
|
||||
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
final UserDetails principal = new User(name, password, grantedAuths);
|
||||
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
|
||||
return auth;
|
||||
} else {
|
||||
if (!"admin".equals(name) || !"system".equals(password)) {
|
||||
return null;
|
||||
}
|
||||
return authenticateAgainstThirdPartyAndGetAuthentication(name, password);
|
||||
}
|
||||
|
||||
private static UsernamePasswordAuthenticationToken authenticateAgainstThirdPartyAndGetAuthentication(String name, String password) {
|
||||
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
|
||||
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
final UserDetails principal = new User(name, password, grantedAuths);
|
||||
return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -2,10 +2,6 @@ package com.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
@ -13,6 +9,10 @@ import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
|
||||
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
|
@ -2,13 +2,13 @@ package com.baeldung.security;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* The Entry Point will not redirect to any sort of Login - it will return the 401
|
||||
*/
|
||||
|
@ -1,27 +1,25 @@
|
||||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.web.dto.Foo;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.web.dto.Foo;
|
||||
|
||||
@Service
|
||||
public class FooService implements IFooService, InitializingBean {
|
||||
|
||||
@Value("${foo1}")
|
||||
private String foo1;
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
private final Environment env;
|
||||
|
||||
public FooService() {
|
||||
public FooService(Environment env) {
|
||||
super();
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public Foo findOne(final Long id) {
|
||||
return new Foo();
|
||||
|
@ -10,8 +10,7 @@ public class RunAsService {
|
||||
|
||||
@Secured({ "ROLE_RUN_AS_REPORTER" })
|
||||
public Authentication getCurrentUser() {
|
||||
Authentication authentication =
|
||||
SecurityContextHolder.getContext().getAuthentication();
|
||||
return authentication;
|
||||
return SecurityContextHolder.getContext()
|
||||
.getAuthentication();
|
||||
}
|
||||
}
|
@ -1,39 +1,34 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.service.IFooService;
|
||||
import com.baeldung.web.dto.Foo;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
@RequestMapping(value = "/foos")
|
||||
public class FooController implements InitializingBean {
|
||||
|
||||
@Value("${foo1}")
|
||||
private String foo1;
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
private final Environment env;
|
||||
private final IFooService service;
|
||||
|
||||
@Autowired
|
||||
private IFooService service;
|
||||
|
||||
public FooController() {
|
||||
public FooController(Environment env, IFooService service) {
|
||||
super();
|
||||
this.env = env;
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public Foo findOne(@PathVariable("id") final Long id) {
|
||||
@GetMapping(value = "/{id}")
|
||||
public Foo findOne(@PathVariable(name = "id") final Long id) {
|
||||
return service.findOne(id);
|
||||
}
|
||||
|
||||
|
@ -2,22 +2,17 @@ package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
public class GetUserWithAuthenticationController {
|
||||
|
||||
public GetUserWithAuthenticationController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/username3", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@GetMapping(value = "/username3")
|
||||
public String currentUserNameSimple(final Authentication authentication) {
|
||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||
System.out.println("Retrieved user with authorities: " + userDetails.getAuthorities());
|
||||
|
@ -1,27 +1,22 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.security.IAuthenticationFacade;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Controller
|
||||
import com.baeldung.security.IAuthenticationFacade;
|
||||
|
||||
@RestController
|
||||
public class GetUserWithCustomInterfaceController {
|
||||
|
||||
@Autowired
|
||||
private IAuthenticationFacade authenticationFacade;
|
||||
private final IAuthenticationFacade authenticationFacade;
|
||||
|
||||
public GetUserWithCustomInterfaceController() {
|
||||
public GetUserWithCustomInterfaceController(IAuthenticationFacade authenticationFacade) {
|
||||
super();
|
||||
this.authenticationFacade = authenticationFacade;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/username5", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@GetMapping(value = "/username5")
|
||||
public String currentUserNameSimple() {
|
||||
final Authentication authentication = authenticationFacade.getAuthentication();
|
||||
return authentication.getName();
|
||||
|
@ -2,24 +2,19 @@ package com.baeldung.web.controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
public class GetUserWithHTTPServletRequestController {
|
||||
|
||||
public GetUserWithHTTPServletRequestController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/username4", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@GetMapping(value = "/username4")
|
||||
public String currentUserNameSimple(final HttpServletRequest request) {
|
||||
final Principal principal = request.getUserPrincipal();
|
||||
return principal.getName();
|
||||
|
@ -2,22 +2,17 @@ package com.baeldung.web.controller;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
public class GetUserWithPrincipalController {
|
||||
|
||||
public GetUserWithPrincipalController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/username2", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@GetMapping(value = "/username2")
|
||||
public String currentUserName(final Principal principal) {
|
||||
return principal.getName();
|
||||
}
|
||||
|
@ -1,29 +1,15 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
public class GetUserWithSecurityContextHolderController {
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
public GetUserWithSecurityContextHolderController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@RequestMapping(value = "/username1", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
@GetMapping(value = "/username1")
|
||||
public String currentUserName() {
|
||||
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (!(authentication instanceof AnonymousAuthenticationToken)) {
|
||||
|
@ -3,18 +3,15 @@ package com.baeldung.web.controller;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
@RequestMapping("/runas")
|
||||
public class RunAsController {
|
||||
|
||||
@Secured({ "ROLE_USER", "RUN_AS_REPORTER" })
|
||||
@RequestMapping
|
||||
@ResponseBody
|
||||
public String tryRunAs() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return "Current User Authorities inside this RunAS method only " +
|
||||
|
@ -1,6 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="https://www.thymeleaf.org"
|
||||
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
|
||||
<html xmlns:sec="https://www.thymeleaf.org">
|
||||
<body>
|
||||
Current user authorities:
|
||||
<span sec:authentication="principal.authorities">user</span>
|
||||
@ -9,7 +8,7 @@
|
||||
<a href="#" onclick="tryRunAs()">Generate Report As Super User</a>
|
||||
|
||||
<script
|
||||
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
|
||||
function tryRunAs(){
|
||||
|
@ -71,6 +71,13 @@
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
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