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>
|
||||
<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>
|
@ -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>
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -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>
|
||||
|
@ -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,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() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -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>
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user