Merge branch 'eugenp:master' into PR-7386
This commit is contained in:
commit
48dc3bbc02
@ -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"));
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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,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,38 @@
|
|||||||
|
package com.baeldung.javatypefromclassinjava;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JavaType;
|
||||||
|
import com.fasterxml.jackson.databind.type.TypeFactory;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
public class JavaTypeFromClassUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGenericClass_whenCreatingJavaType_thenJavaTypeNotNull() {
|
||||||
|
Class<?> myClass = MyGenericClass.class;
|
||||||
|
|
||||||
|
JavaType javaType = TypeFactory.defaultInstance().constructType(myClass);
|
||||||
|
|
||||||
|
assertNotNull(javaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenParametricType_whenCreatingJavaType_thenJavaTypeNotNull() {
|
||||||
|
Class<?> containerClass = Container.class;
|
||||||
|
Class<?> elementType = String.class;
|
||||||
|
|
||||||
|
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(containerClass, elementType);
|
||||||
|
|
||||||
|
assertNotNull(javaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
static class MyGenericClass<T> {
|
||||||
|
// Class implementation
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Container<T> {
|
||||||
|
// Class implementation
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -95,6 +95,12 @@
|
|||||||
<artifactId>protobuf-java</artifactId>
|
<artifactId>protobuf-java</artifactId>
|
||||||
<version>${google-protobuf.version}</version>
|
<version>${google-protobuf.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- jetcd core api -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.etcd</groupId>
|
||||||
|
<artifactId>jetcd-core</artifactId>
|
||||||
|
<version>${jetcd-version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
@ -110,6 +116,7 @@
|
|||||||
<yamlbeans.version>1.15</yamlbeans.version>
|
<yamlbeans.version>1.15</yamlbeans.version>
|
||||||
<apache-thrift.version>0.14.2</apache-thrift.version>
|
<apache-thrift.version>0.14.2</apache-thrift.version>
|
||||||
<google-protobuf.version>3.17.3</google-protobuf.version>
|
<google-protobuf.version>3.17.3</google-protobuf.version>
|
||||||
|
<jetcd-version>0.7.7</jetcd-version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.etcd;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
import io.etcd.jetcd.kv.GetResponse;
|
||||||
|
import io.etcd.jetcd.ByteSequence;
|
||||||
|
import io.etcd.jetcd.KV;
|
||||||
|
import io.etcd.jetcd.Client;
|
||||||
|
|
||||||
|
public class JetcdExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String etcdEndpoint = "http://localhost:2379";
|
||||||
|
ByteSequence key = ByteSequence.from("/mykey".getBytes());
|
||||||
|
ByteSequence value = ByteSequence.from("Hello, etcd!".getBytes());
|
||||||
|
|
||||||
|
try (Client client = Client.builder().endpoints(etcdEndpoint).build()) {
|
||||||
|
KV kvClient = client.getKVClient();
|
||||||
|
|
||||||
|
// Put a key-value pair
|
||||||
|
kvClient.put(key, value).get();
|
||||||
|
|
||||||
|
// Retrieve the value using CompletableFuture
|
||||||
|
CompletableFuture<GetResponse> getFuture = kvClient.get(key);
|
||||||
|
GetResponse response = getFuture.get();
|
||||||
|
|
||||||
|
// Delete the key
|
||||||
|
kvClient.delete(key).get();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -62,6 +62,11 @@
|
|||||||
<artifactId>modelmapper</artifactId>
|
<artifactId>modelmapper</artifactId>
|
||||||
<version>${modelmapper.version}</version>
|
<version>${modelmapper.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
@ -88,6 +93,7 @@
|
|||||||
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
||||||
<jackson.version>2.16.0</jackson.version>
|
<jackson.version>2.16.0</jackson.version>
|
||||||
<modelmapper.version>3.2.0</modelmapper.version>
|
<modelmapper.version>3.2.0</modelmapper.version>
|
||||||
|
<commons-codec.version>1.16.1</commons-codec.version>
|
||||||
<lombok.version>1.18.30</lombok.version>
|
<lombok.version>1.18.30</lombok.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class CustomFunctionApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(CustomFunctionApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.hibernate.boot.model.FunctionContributions;
|
||||||
|
import org.hibernate.dialect.H2Dialect;
|
||||||
|
|
||||||
|
import org.hibernate.query.sqm.function.FunctionKind;
|
||||||
|
import org.hibernate.query.sqm.function.SqmFunctionRegistry;
|
||||||
|
import org.hibernate.query.sqm.produce.function.PatternFunctionDescriptorBuilder;
|
||||||
|
import org.hibernate.type.spi.TypeConfiguration;
|
||||||
|
|
||||||
|
public class CustomH2Dialect extends H2Dialect {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void initializeFunctionRegistry(FunctionContributions functionContributions) {
|
||||||
|
super.initializeFunctionRegistry(functionContributions);
|
||||||
|
SqmFunctionRegistry registry = functionContributions.getFunctionRegistry();
|
||||||
|
TypeConfiguration types = functionContributions.getTypeConfiguration();
|
||||||
|
|
||||||
|
new PatternFunctionDescriptorBuilder(registry, "sha256hex", FunctionKind.NORMAL, "SHA256_HEX(?1)")
|
||||||
|
.setExactArgumentCount(1)
|
||||||
|
.setInvariantType(types.getBasicTypeForJavaType(String.class))
|
||||||
|
.register();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CustomHibernateConfig implements HibernatePropertiesCustomizer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void customize(Map<String, Object> hibernateProperties) {
|
||||||
|
hibernateProperties.put("hibernate.dialect", "com.baeldung.customfunc.CustomH2Dialect");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "product")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@EqualsAndHashCode(of = {"id"})
|
||||||
|
@NamedStoredProcedureQuery(
|
||||||
|
name = "Product.sha256Hex",
|
||||||
|
procedureName = "SHA256_HEX",
|
||||||
|
parameters = @StoredProcedureParameter(mode = ParameterMode.IN, name = "value", type = String.class)
|
||||||
|
)
|
||||||
|
public class Product {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "product_id")
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.jpa.repository.query.Procedure;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface ProductRepository extends JpaRepository<Product, Integer> {
|
||||||
|
|
||||||
|
@Procedure(name = "Product.sha256Hex")
|
||||||
|
String getSha256HexByNamedMapping(@Param("value") String value);
|
||||||
|
|
||||||
|
@Query(value = "CALL SHA256_HEX(:value)", nativeQuery = true)
|
||||||
|
String getSha256HexByNativeCall(@Param("value") String value);
|
||||||
|
|
||||||
|
@Query(value = "SELECT SHA256_HEX(name) FROM product", nativeQuery = true)
|
||||||
|
List<String> getProductNameListInSha256HexByNativeSelect();
|
||||||
|
|
||||||
|
@Query(value = "SELECT sha256Hex(p.name) FROM Product p")
|
||||||
|
List<String> getProductNameListInSha256Hex();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.customfunc;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||||
|
|
||||||
|
@SpringBootTest(classes = CustomFunctionApplication.class, properties = {
|
||||||
|
"spring.jpa.show-sql=true",
|
||||||
|
"spring.jpa.properties.hibernate.format_sql=true",
|
||||||
|
"spring.jpa.generate-ddl=true",
|
||||||
|
"spring.jpa.defer-datasource-initialization=true",
|
||||||
|
"spring.sql.init.data-locations=classpath:product-data.sql"
|
||||||
|
})
|
||||||
|
@Transactional
|
||||||
|
public class ProductRepositoryIntegrationTest {
|
||||||
|
|
||||||
|
private static final String TEXT = "Hand Grip Strengthener";
|
||||||
|
private static final String EXPECTED_HASH_HEX = getSha256Hex(TEXT);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ProductRepository productRepository;
|
||||||
|
|
||||||
|
private static String getSha256Hex(String value) {
|
||||||
|
return Hex.encodeHexString(DigestUtils.sha256(value.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenGetSha256HexByNamedMapping_thenReturnCorrectHash() {
|
||||||
|
var hash = productRepository.getSha256HexByNamedMapping(TEXT);
|
||||||
|
assertThat(hash).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenGetSha256HexByNativeCall_thenReturnCorrectHash() {
|
||||||
|
var hash = productRepository.getSha256HexByNativeCall(TEXT);
|
||||||
|
assertThat(hash).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallGetSha256HexNative_thenReturnCorrectHash() {
|
||||||
|
var hashList = productRepository.getProductNameListInSha256HexByNativeSelect();
|
||||||
|
assertThat(hashList.get(0)).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallGetSha256Hex_thenReturnCorrectHash() {
|
||||||
|
var hashList = productRepository.getProductNameListInSha256Hex();
|
||||||
|
assertThat(hashList.get(0)).isEqualTo(EXPECTED_HASH_HEX);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
CREATE ALIAS SHA256_HEX AS '
|
||||||
|
import java.sql.*;
|
||||||
|
@CODE
|
||||||
|
String getSha256Hex(Connection conn, String value) throws SQLException {
|
||||||
|
var sql = "SELECT RAWTOHEX(HASH(''SHA-256'', ?))";
|
||||||
|
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||||
|
stmt.setString(1, value);
|
||||||
|
ResultSet rs = stmt.executeQuery();
|
||||||
|
if (rs.next()) {
|
||||||
|
return rs.getString(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
';
|
||||||
|
|
||||||
|
INSERT INTO product(name) VALUES('Hand Grip Strengthener');
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.boot.connection.via.builder;
|
||||||
|
|
||||||
|
import com.mongodb.ConnectionString;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringMongoConnectionViaBuilderApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaBuilderApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MongoClientSettingsBuilderCustomizer customizer(@Value("${custom.uri}") String uri) {
|
||||||
|
ConnectionString connection = new ConnectionString(uri);
|
||||||
|
return settings -> settings.applyConnectionString(connection);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.boot.connection.via.client;
|
||||||
|
|
||||||
|
import com.mongodb.client.ListDatabasesIterable;
|
||||||
|
import com.mongodb.client.MongoClient;
|
||||||
|
import com.mongodb.client.MongoClients;
|
||||||
|
import org.bson.Document;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||||
|
|
||||||
|
@SpringBootApplication(exclude={EmbeddedMongoAutoConfiguration.class})
|
||||||
|
public class SpringMongoConnectionViaClientApp extends AbstractMongoClientConfiguration {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Value("${spring.data.mongodb.uri}")
|
||||||
|
private String uri;
|
||||||
|
|
||||||
|
@Value("${spring.data.mongodb.database}")
|
||||||
|
private String db;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public MongoClient mongoClient() {
|
||||||
|
MongoClient client = MongoClients.create(uri);
|
||||||
|
ListDatabasesIterable<Document> databases = client.listDatabases();
|
||||||
|
databases.forEach(System.out::println);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getDatabaseName() {
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.boot.connection.via.factory;
|
||||||
|
|
||||||
|
import com.mongodb.ConnectionString;
|
||||||
|
import com.mongodb.client.MongoClient;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringMongoConnectionViaFactoryApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaFactoryApp.class);
|
||||||
|
app.web(WebApplicationType.NONE);
|
||||||
|
app.run(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public MongoClientFactoryBean mongo(@Value("${custom.uri}") String uri) throws Exception {
|
||||||
|
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
|
||||||
|
ConnectionString conn = new ConnectionString(uri);
|
||||||
|
mongo.setConnectionString(conn);
|
||||||
|
|
||||||
|
mongo.setSingleton(false);
|
||||||
|
|
||||||
|
MongoClient client = mongo.getObject();
|
||||||
|
client.listDatabaseNames()
|
||||||
|
.forEach(System.out::println);
|
||||||
|
return mongo;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.boot.connection.via.properties;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
|
||||||
|
@PropertySource("classpath:connection.via.properties/application.properties")
|
||||||
|
@SpringBootApplication(exclude={EmbeddedMongoAutoConfiguration.class})
|
||||||
|
public class SpringMongoConnectionViaPropertiesApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
SpringApplication.run(SpringMongoConnectionViaPropertiesApp.class, args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
spring.data.mongodb.host=localhost
|
||||||
|
spring.data.mongodb.port=27017
|
||||||
|
spring.data.mongodb.database=baeldung
|
||||||
|
spring.data.mongodb.username=admin
|
||||||
|
spring.data.mongodb.password=password
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.boot.connection.via;
|
||||||
|
|
||||||
|
import com.baeldung.boot.connection.via.client.SpringMongoConnectionViaClientApp;
|
||||||
|
import com.baeldung.boot.connection.via.properties.SpringMongoConnectionViaPropertiesApp;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.BeanCreationException;
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class MongoConnectionApplicationLiveTest {
|
||||||
|
private static final String HOST = "localhost";
|
||||||
|
private static final String PORT = "27017";
|
||||||
|
private static final String DB = "baeldung";
|
||||||
|
private static final String USER = "admin";
|
||||||
|
private static final String PASS = "password";
|
||||||
|
|
||||||
|
private void assertInsertSucceeds(ConfigurableApplicationContext context) {
|
||||||
|
String name = "A";
|
||||||
|
|
||||||
|
MongoTemplate mongo = context.getBean(MongoTemplate.class);
|
||||||
|
Document doc = Document.parse("{\"name\":\"" + name + "\"}");
|
||||||
|
Document inserted = mongo.insert(doc, "items");
|
||||||
|
|
||||||
|
assertNotNull(inserted.get("_id"));
|
||||||
|
assertEquals(inserted.get("name"), name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPropertiesConfig_thenInsertSucceeds() {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
|
||||||
|
app.run();
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrecedence_whenSystemConfig_thenInsertSucceeds() {
|
||||||
|
System.setProperty("spring.data.mongodb.host", HOST);
|
||||||
|
System.setProperty("spring.data.mongodb.port", PORT);
|
||||||
|
System.setProperty("spring.data.mongodb.database", DB);
|
||||||
|
System.setProperty("spring.data.mongodb.username", USER);
|
||||||
|
System.setProperty("spring.data.mongodb.password", PASS);
|
||||||
|
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
|
||||||
|
.properties(
|
||||||
|
"spring.data.mongodb.host=oldValue",
|
||||||
|
"spring.data.mongodb.port=oldValue",
|
||||||
|
"spring.data.mongodb.database=oldValue",
|
||||||
|
"spring.data.mongodb.username=oldValue",
|
||||||
|
"spring.data.mongodb.password=oldValue"
|
||||||
|
);
|
||||||
|
app.run();
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConnectionUri_whenAlsoIncludingIndividualParameters_thenInvalidConfig() {
|
||||||
|
System.setProperty(
|
||||||
|
"spring.data.mongodb.uri",
|
||||||
|
"mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
|
||||||
|
);
|
||||||
|
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
|
||||||
|
.properties(
|
||||||
|
"spring.data.mongodb.host=" + HOST,
|
||||||
|
"spring.data.mongodb.port=" + PORT,
|
||||||
|
"spring.data.mongodb.username=" + USER,
|
||||||
|
"spring.data.mongodb.password=" + PASS
|
||||||
|
);
|
||||||
|
|
||||||
|
BeanCreationException e = assertThrows(BeanCreationException.class, () -> {
|
||||||
|
app.run();
|
||||||
|
});
|
||||||
|
|
||||||
|
Throwable rootCause = e.getRootCause();
|
||||||
|
assertTrue(rootCause instanceof IllegalStateException);
|
||||||
|
assertThat(rootCause.getMessage()
|
||||||
|
.contains("Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenClientConfig_thenInsertSucceeds() {
|
||||||
|
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
|
||||||
|
app.web(WebApplicationType.NONE)
|
||||||
|
.run(
|
||||||
|
"--spring.data.mongodb.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB,
|
||||||
|
"--spring.data.mongodb.database=" + DB
|
||||||
|
);
|
||||||
|
|
||||||
|
assertInsertSucceeds(app.context());
|
||||||
|
}
|
||||||
|
}
|
@ -194,7 +194,7 @@
|
|||||||
<lifecycle-mapping.version>1.0.0</lifecycle-mapping.version>
|
<lifecycle-mapping.version>1.0.0</lifecycle-mapping.version>
|
||||||
<sql-maven-plugin.version>1.5</sql-maven-plugin.version>
|
<sql-maven-plugin.version>1.5</sql-maven-plugin.version>
|
||||||
<properties-maven-plugin.version>1.0.0</properties-maven-plugin.version>
|
<properties-maven-plugin.version>1.0.0</properties-maven-plugin.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
<h2.version>2.2.224</h2.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -19,12 +19,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-context</artifactId>
|
<artifactId>spring-context</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-beans</artifactId>
|
<artifactId>spring-beans</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- SpringBoot -->
|
<!-- SpringBoot -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -36,12 +34,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
<version>${h2.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-jdbc</artifactId>
|
<artifactId>spring-jdbc</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mybatis</groupId>
|
<groupId>org.mybatis</groupId>
|
||||||
@ -61,7 +57,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -77,14 +72,10 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Spring -->
|
|
||||||
<org.springframework.version>6.0.13</org.springframework.version>
|
|
||||||
<!-- persistence -->
|
|
||||||
<spring-mybatis.version>3.0.3</spring-mybatis.version>
|
<spring-mybatis.version>3.0.3</spring-mybatis.version>
|
||||||
<mybatis.version>3.5.2</mybatis.version>
|
<mybatis.version>3.5.2</mybatis.version>
|
||||||
<mybatis-spring-boot-starter.version>3.0.3</mybatis-spring-boot-starter.version>
|
<mybatis-spring-boot-starter.version>3.0.3</mybatis-spring-boot-starter.version>
|
||||||
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
|
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,7 +1,7 @@
|
|||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<title>WebJars Demo</title>
|
<title>WebJars Demo</title>
|
||||||
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
|
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Welcome Home</h1>
|
<h1>Welcome Home</h1>
|
||||||
@ -12,8 +12,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
|
<script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
|
||||||
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
|
<script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -104,6 +104,13 @@
|
|||||||
<useDefaultDelimiters>false</useDefaultDelimiters>
|
<useDefaultDelimiters>false</useDefaultDelimiters>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<parameters>true</parameters>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
@ -142,12 +149,11 @@
|
|||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud.version>2022.0.4</spring-cloud.version>
|
<spring-cloud.version>2023.0.0</spring-cloud.version>
|
||||||
<commons-configuration.version>1.10</commons-configuration.version>
|
<commons-configuration.version>1.10</commons-configuration.version>
|
||||||
<resource.delimiter>@</resource.delimiter>
|
<resource.delimiter>@</resource.delimiter>
|
||||||
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
|
<!-- <start-class>com.baeldung.buildproperties.Application</start-class> -->
|
||||||
<start-class>com.baeldung.yaml.MyApplication</start-class>
|
<start-class>com.baeldung.yaml.MyApplication</start-class>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -53,7 +53,6 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<apache.client5.version>5.0.3</apache.client5.version>
|
<apache.client5.version>5.0.3</apache.client5.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -27,7 +27,7 @@ public class SecureRestTemplateConfig {
|
|||||||
this.sslContext = sslBundle.createSslContext();
|
this.sslContext = sslBundle.createSslContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean(name="secureRestTemplate")
|
||||||
public RestTemplate secureRestTemplate() {
|
public RestTemplate secureRestTemplate() {
|
||||||
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext).build();
|
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext).build();
|
||||||
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
|
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.springbootsslbundles;
|
package com.baeldung.springbootsslbundles;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@ -11,7 +12,7 @@ public class SecureServiceRestApi {
|
|||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public SecureServiceRestApi(RestTemplate restTemplate) {
|
public SecureServiceRestApi(@Qualifier("secureRestTemplate") RestTemplate restTemplate) {
|
||||||
this.restTemplate = restTemplate;
|
this.restTemplate = restTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,9 +10,10 @@
|
|||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-modules</artifactId>
|
<artifactId>parent-boot-3</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-3</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
@ -35,7 +36,7 @@
|
|||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<spring-cloud-dependencies.version>2021.0.3</spring-cloud-dependencies.version>
|
<spring-cloud-dependencies.version>2022.0.3</spring-cloud-dependencies.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.config.server;
|
|||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.Customizer;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
@ -10,13 +11,13 @@ public class SecurityConfiguration {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.csrf()
|
http.csrf(csrf -> csrf.ignoringRequestMatchers(
|
||||||
.ignoringAntMatchers("/encrypt/**")
|
"/encrypt/**", "/decrypt/**"
|
||||||
.ignoringAntMatchers("/decrypt/**");
|
))
|
||||||
http.authorizeRequests((requests) -> requests.anyRequest()
|
.authorizeRequests(authz -> authz.anyRequest().authenticated())
|
||||||
.authenticated());
|
.formLogin(Customizer.withDefaults())
|
||||||
http.formLogin();
|
.httpBasic(Customizer.withDefaults());
|
||||||
http.httpBasic();
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Sample Client</description>
|
<description>Spring Cloud Eureka Sample Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Sample Client</description>
|
<description>Spring Cloud Eureka Sample Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka - Feign Client Integration Tests</description>
|
<description>Spring Cloud Eureka - Feign Client Integration Tests</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka - Sample Feign Client</description>
|
<description>Spring Cloud Eureka - Sample Feign Client</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -10,7 +10,7 @@
|
|||||||
<description>Spring Cloud Eureka Server Demo</description>
|
<description>Spring Cloud Eureka Server Demo</description>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.spring.cloud</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>spring-cloud-eureka</artifactId>
|
<artifactId>spring-cloud-eureka</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
@ -38,7 +38,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate.orm</groupId>
|
<groupId>org.hibernate.orm</groupId>
|
||||||
<artifactId>hibernate-core</artifactId>
|
<artifactId>hibernate-core</artifactId>
|
||||||
<version>${hibernate-core.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Testing -->
|
<!-- Testing -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -65,7 +64,6 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<jinq.version>2.0.1</jinq.version>
|
<jinq.version>2.0.1</jinq.version>
|
||||||
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
|
<hibernate-core.version>6.4.2.Final</hibernate-core.version>
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,4 +1,4 @@
|
|||||||
spring.kafka.bootstrap-servers=localhost:9092,localhost:9093,localhost:9094,localhost:9095
|
spring.kafka.bootstrap-servers=localhost:9092,localhost:9093,localhost:9094
|
||||||
message.topic.name=baeldung
|
message.topic.name=baeldung
|
||||||
long.message.topic.name=longMessage
|
long.message.topic.name=longMessage
|
||||||
greeting.topic.name=greeting
|
greeting.topic.name=greeting
|
||||||
|
@ -26,7 +26,8 @@ import com.baeldung.spring.kafka.dlt.listener.PaymentListenerDltRetryOnError;
|
|||||||
import com.baeldung.spring.kafka.dlt.listener.PaymentListenerNoDlt;
|
import com.baeldung.spring.kafka.dlt.listener.PaymentListenerNoDlt;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
@SpringBootTest(classes = KafkaDltApplication.class)
|
@SpringBootTest(classes = KafkaDltApplication.class,
|
||||||
|
properties = "spring.kafka.bootstrap-servers=localhost:9095")
|
||||||
@EmbeddedKafka(
|
@EmbeddedKafka(
|
||||||
partitions = 1,
|
partitions = 1,
|
||||||
brokerProperties = { "listeners=PLAINTEXT://localhost:9095", "port=9095" },
|
brokerProperties = { "listeners=PLAINTEXT://localhost:9095", "port=9095" },
|
||||||
|
@ -21,7 +21,8 @@ import org.springframework.kafka.test.context.EmbeddedKafka;
|
|||||||
import org.springframework.kafka.test.utils.ContainerTestUtils;
|
import org.springframework.kafka.test.utils.ContainerTestUtils;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
@SpringBootTest(classes = KafkaMultipleTopicsApplication.class)
|
@SpringBootTest(classes = KafkaMultipleTopicsApplication.class,
|
||||||
|
properties = "spring.kafka.bootstrap-servers=localhost:9099")
|
||||||
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" })
|
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" })
|
||||||
@ActiveProfiles("multipletopics")
|
@ActiveProfiles("multipletopics")
|
||||||
public class KafkaMultipleTopicsIntegrationTest {
|
public class KafkaMultipleTopicsIntegrationTest {
|
||||||
|
@ -51,11 +51,14 @@
|
|||||||
<layout>JAR</layout>
|
<layout>JAR</layout>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<parameters>true</parameters>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<spring-boot.version>3.1.5</spring-boot.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -10,9 +10,9 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-spring-5</artifactId>
|
<artifactId>parent-spring-6</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-spring-5</relativePath>
|
<relativePath>../../parent-spring-6</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -20,17 +20,17 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-web</artifactId>
|
<artifactId>spring-security-web</artifactId>
|
||||||
<version>${spring-security.version}</version>
|
<version>${spring.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-config</artifactId>
|
<artifactId>spring-security-config</artifactId>
|
||||||
<version>${spring-security.version}</version>
|
<version>${spring.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-taglibs</artifactId>
|
<artifactId>spring-security-taglibs</artifactId>
|
||||||
<version>${spring-security.version}</version>
|
<version>${spring.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Spring -->
|
<!-- Spring -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -65,22 +65,21 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>jakarta.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>jakarta.servlet-api</artifactId>
|
||||||
<version>${javax.servlet-api.version}</version>
|
<version>${jakarta-servlet-api.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>jakarta.servlet.jsp.jstl</groupId>
|
||||||
<artifactId>jstl</artifactId>
|
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
|
||||||
<version>${jstl.version}</version>
|
<version>${jakarta-servlet-jsp.version}</version>
|
||||||
<scope>runtime</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Test -->
|
<!-- Test -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<version>${spring-boot-starter-test.version}</version>
|
<version>${spring-boot.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -153,6 +152,8 @@
|
|||||||
<!-- frontend -->
|
<!-- frontend -->
|
||||||
<node.version>v8.11.3</node.version>
|
<node.version>v8.11.3</node.version>
|
||||||
<npm.version>6.1.0</npm.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,5 +1,4 @@
|
|||||||
package com.baeldung.spring;
|
package com.baeldung.spring;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
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.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
@RequestMapping("/rest")
|
@RequestMapping("/rest")
|
||||||
public class RestController {
|
public class RestController {
|
||||||
|
@ -38,28 +38,21 @@ public class SecSecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.csrf()
|
return http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
|
||||||
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
.authorizeHttpRequests(request -> request.requestMatchers("/admin/**")
|
||||||
.and()
|
.hasRole("ADMIN")
|
||||||
.authorizeRequests()
|
.requestMatchers("/anonymous*")
|
||||||
.antMatchers("/admin/**")
|
.anonymous()
|
||||||
.hasRole("ADMIN")
|
.requestMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest")
|
||||||
.antMatchers("/anonymous*")
|
.permitAll()
|
||||||
.anonymous()
|
.anyRequest()
|
||||||
.antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/rest")
|
.authenticated())
|
||||||
.permitAll()
|
.formLogin(form -> form.loginPage("/index.html")
|
||||||
.anyRequest()
|
.loginProcessingUrl("/perform_login")
|
||||||
.authenticated()
|
.defaultSuccessUrl("/homepage.html", true)
|
||||||
.and()
|
.failureUrl("/index.html?error=true"))
|
||||||
.formLogin()
|
.logout(logout -> logout.logoutUrl("/perform_logout")
|
||||||
.loginPage("/index.html")
|
.deleteCookies("JSESSIONID"))
|
||||||
.loginProcessingUrl("/perform_login")
|
.build();
|
||||||
.defaultSuccessUrl("/homepage.html", true)
|
|
||||||
.failureUrl("/index.html?error=true")
|
|
||||||
.and()
|
|
||||||
.logout()
|
|
||||||
.logoutUrl("/perform_logout")
|
|
||||||
.deleteCookies("JSESSIONID");
|
|
||||||
return http.build();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,19 +1,22 @@
|
|||||||
package com.baeldung;
|
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.MvcConfig;
|
||||||
import com.baeldung.spring.SecSecurityConfig;
|
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
|
@WebAppConfiguration
|
||||||
@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class })
|
@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class })
|
||||||
public class SpringContextTest {
|
@ExtendWith(SpringExtension.class)
|
||||||
|
class SpringContextTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -71,6 +71,13 @@
|
|||||||
<skip>true</skip>
|
<skip>true</skip>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<parameters>true</parameters>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user