This commit is contained in:
Philippe Sevestre 2024-02-21 23:01:37 -03:00
commit 050ea28903
121 changed files with 2205 additions and 349 deletions

View File

@ -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));
}
}

View File

@ -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"));
}
}

View File

@ -19,10 +19,29 @@
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-junit5</artifactId>
<version>${camel.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-main</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
<properties>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
<camel.version>4.3.0</camel.version>
</properties>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.dynamicrouter;
import org.apache.camel.ExchangeProperties;
import java.util.Map;
public class DynamicRouterBean {
public String route(String body, @ExchangeProperties Map<String, Object> properties) {
int invoked = (int) properties.getOrDefault("invoked", 0) + 1;
properties.put("invoked", invoked);
if (invoked == 1) {
switch (body.toLowerCase()) {
case "mock":
return "mock:dynamicRouter";
case "direct":
return "mock:directDynamicRouter";
case "seda":
return "mock:sedaDynamicRouter";
case "file":
return "mock:fileDynamicRouter";
default:
break;
}
}
return null;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.dynamicrouter;
import org.apache.camel.builder.RouteBuilder;
public class DynamicRouterRoute extends RouteBuilder {
@Override
public void configure() {
from("direct:dynamicRouter").dynamicRouter(method(DynamicRouterBean.class, "route"));
}
}

View File

@ -10,4 +10,6 @@
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.apache.camel.impl.engine" level="WARN"/>
</configuration>

View File

@ -0,0 +1,61 @@
package dynamicrouter;
import com.baeldung.dynamicrouter.DynamicRouterRoute;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
public class DynamicRouterRouteUnitTest extends CamelTestSupport {
@Override
protected RoutesBuilder createRouteBuilder() {
return new DynamicRouterRoute();
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndMockAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:dynamicRouter");
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("mock"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndDirectAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:directDynamicRouter", MockEndpoint.class);
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("direct"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndSedaAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:sedaDynamicRouter", MockEndpoint.class);
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("seda"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndBookAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:fileDynamicRouter");
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("file"));
MockEndpoint.assertIsSatisfied(context);
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<logger name="ch.qos.logback.classic.joran.action" level="WARN"/>
</configuration>

View File

@ -1,61 +1,71 @@
package com.baeldung.io
import org.junit.Test
import groovy.io.FileType
import groovy.io.FileVisitResult
import org.junit.Test
import static org.junit.Assert.assertTrue
class TraverseFileTreeUnitTest {
@Test
void whenUsingEachFile_filesAreListed() {
var files = []
new File('src/main/resources').eachFile { file ->
println file.name
files.add(file.name)
}
assertTrue(files.size() > 1)
}
@Test(expected = IllegalArgumentException)
void whenUsingEachFileOnAFile_anErrorOccurs() {
var files = []
new File('src/main/resources/ioInput.txt').eachFile { file ->
println file.name
files.add(file.name)
}
}
@Test
void whenUsingEachFileMatch_filesAreListed() {
var files = []
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
println file.name
files.add(file.name)
}
}
@Test
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
var files = []
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
println "$file.parent $file.name"
files.add("$file.parent $file.name")
}
}
@Test
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
var files = []
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
println "$file.parent $file.name"
files.add("$file.parent $file.name")
}
}
@Test
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
var files = []
new File('src/main').eachDirRecurse { dir ->
println "$dir.parent $dir.name"
files.add("$dir.parent $dir.name")
}
}
@Test
void whenUsingTraverse_thenDirectoryIsTraversed() {
var files = []
new File('src/main').traverse { file ->
if (file.directory && file.name == 'groovy') {
FileVisitResult.SKIP_SUBTREE
} else {
println "$file.parent - $file.name"
files.add("$file.parent - $file.name")
}
}
assertTrue(files.size() > 1)
}
}

View File

@ -2,6 +2,8 @@ package groovy.com.baeldung.stringtypes
import org.junit.Test
import static org.junit.Assert.assertFalse
class DollarSlashyString {
@Test
@ -19,6 +21,7 @@ class DollarSlashyString {
- $/$$
/$
print(dollarSlashy)
//print(dollarSlashy)
assertFalse(dollarSlashy.isEmpty())
}
}

View File

@ -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);
}
}

View File

@ -60,14 +60,15 @@ public class HashtableUnitTest {
table.put(new Word("dog"), "another animal");
Iterator<Word> it = table.keySet().iterator();
System.out.println("iterator created");
// System.out.println("iterator created");
table.remove(new Word("dog"));
System.out.println("element removed");
// System.out.println("element removed");
while (it.hasNext()) {
Word key = it.next();
System.out.println(table.get(key));
// System.out.println(table.get(key));
assertNotNull(table.get(key));
}
}
@ -85,12 +86,13 @@ public class HashtableUnitTest {
table.put(new Word("8"), "eight");
Enumeration<Word> enumKey = table.keys();
System.out.println("Enumeration created");
// System.out.println("Enumeration created");
table.remove(new Word("1"));
System.out.println("element removed");
// System.out.println("element removed");
while (enumKey.hasMoreElements()) {
Word key = enumKey.nextElement();
System.out.println(table.get(key));
// System.out.println(table.get(key));
assertNotNull(table.get(key));
}
}
@ -110,7 +112,8 @@ public class HashtableUnitTest {
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Word, String> entry = it.next();
System.out.println(entry.getValue());
// System.out.println(entry.getValue());
assertNotNull(entry.getValue());
}
}

View File

@ -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);
});
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.eclipse.jetty.server.handler" level="WARN"/>
<logger name="org.mockserver.log" level="WARN"/>
</configuration>

View File

@ -23,9 +23,9 @@ public class SSLDebugLogger {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
logger.info("Response from " + url + ":");
logger.debug("Response from " + url + ":");
while ((line = reader.readLine()) != null) {
logger.info(line);
logger.debug(line);
}
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -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);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.checkifstringisbased64;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*;
public class CheckIfStringIsBased64UnitTest {
@Test
public void givenBase64EncodedString_whenDecoding_thenNoException() {
try {
Base64.getDecoder().decode("SGVsbG8gd29ybGQ=");
assertTrue(true);
} catch (IllegalArgumentException e) {
fail("Unexpected exception: " + e.getMessage());
}
}
@Test
public void givenNonBase64String_whenDecoding_thenCatchException() {
try {
Base64.getDecoder().decode("Hello world!");
fail("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
public void givenString_whenOperatingRegex_thenCheckIfItIsBase64Encoded() {
Pattern BASE64_PATTERN = Pattern.compile(
"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
);
assertTrue(BASE64_PATTERN.matcher("SGVsbG8gd29ybGQ=").matches());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.finduniqueemails;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FindUniqueEmailsUnitTest {
String[] emailList = {"user@example.com", "user@example.com", "user@gmail.com", "admin@example.com", "USER@example.com"};
Set<String> expectedUniqueEmails = new HashSet<>();
FindUniqueEmailsUnitTest() {
expectedUniqueEmails.add("user@example.com");
expectedUniqueEmails.add("user@gmail.com");
expectedUniqueEmails.add("admin@example.com");
}
@Test
public void givenEmailList_whenUsingStringManipulation_thenFindUniqueEmails() {
Set<String> uniqueEmails = new HashSet<>();
for (String email : emailList) {
uniqueEmails.add(email.toLowerCase());
}
assertEquals(expectedUniqueEmails, uniqueEmails);
}
@Test
public void givenEmailList_whenUsingJavaStreams_thenFindUniqueEmails() {
Set<String> uniqueEmails = Arrays.stream(emailList)
.map(String::toLowerCase)
.collect(Collectors.toSet());
assertEquals(expectedUniqueEmails, uniqueEmails);
}
}

View File

@ -1,4 +1,4 @@
FROM openjdk:11
FROM openjdk:17-alpine
MAINTAINER baeldung.com
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>

View File

@ -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
}
}

View File

@ -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>

View File

@ -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();
}
}
}

View File

@ -48,6 +48,7 @@
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-jms-server</artifactId>
<version>${activemq.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -65,4 +66,8 @@
</plugins>
</build>
<properties>
<activemq.version>2.32.0</activemq.version>
</properties>
</project>

View File

@ -0,0 +1,69 @@
package com.baeldung.findby;
import jakarta.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "ACCOUNTS")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "accounts_seq")
@SequenceGenerator(name = "accounts_seq", sequenceName = "accounts_seq", allocationSize = 1)
@Column(name = "user_id")
private int userId;
private String username;
private String password;
private String email;
private Timestamp createdOn;
private Timestamp lastLogin;
@OneToOne
@JoinColumn(name = "permissions_id")
private Permission permission;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public void setLastLogin(Timestamp lastLogin) {
this.lastLogin = lastLogin;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Account{" + "userId=" + userId + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", createdOn=" + createdOn + ", lastLogin=" + lastLogin + ", permission=" + permission + '}';
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.findby;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.findby;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AccountRepository extends JpaRepository<Account, Integer> {
Account findByEmail(String email);
Account findByUsernameAndEmail(String username, String email);
Account findByUsernameOrEmail(String username, String email);
List<Account> findByUsernameInOrEmailIn(List<String> usernames, List<String> emails);
}

View File

@ -0,0 +1,24 @@
package com.baeldung.findby;
import jakarta.persistence.*;
@Entity
@Table(name = "PERMISSIONS")
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "permissions_id_sq")
@SequenceGenerator(name = "permissions_id_sq", sequenceName = "permissions_id_sq", allocationSize = 1)
private int id;
private String type;
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Permission{" + "id=" + id + ", type='" + type + '\'' + '}';
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.findby;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PermissionRepository extends JpaRepository<Permission, Integer> {
Permission findByType(String type);
}

View File

@ -0,0 +1,105 @@
package com.baeldung.boot.findby;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.findby.Account;
import com.baeldung.findby.AccountApplication;
import com.baeldung.findby.AccountRepository;
import com.baeldung.findby.Permission;
import com.baeldung.findby.PermissionRepository;
@SpringBootTest(classes = AccountApplication.class)
public class AccountRepositoryUnitTest {
@Autowired
private AccountRepository accountRepository;
@Autowired
private PermissionRepository permissionRepository;
@BeforeEach
void setup() {
saveAccount();
}
@AfterEach
void tearDown() {
accountRepository.deleteAll();
permissionRepository.deleteAll();
}
@Test
void givenAccountInDb_whenPerformFindByEmail_thenReturnsAccount() {
String email = "test@test.com";
Account account = accountRepository.findByEmail(email);
assertThat(account.getEmail()).isEqualTo(email);
}
@Test
void givenAccountInDb_whenPerformFindByUsernameAndEmail_thenReturnsAccount() {
String email = "test@test.com";
String username = "user_admin";
Account account = accountRepository.findByUsernameAndEmail(username, email);
assertThat(account.getUsername()).isEqualTo(username);
assertThat(account.getEmail()).isEqualTo(email);
}
@Test
void givenAccountInDb_whenPerformFindByUsernameOrEmail_thenReturnsAccount() {
String email = "test@test.com";
String username = "user_editor";
Account account = accountRepository.findByUsernameOrEmail(username, email);
assertThat(account.getUsername()).isNotEqualTo(username);
assertThat(account.getEmail()).isEqualTo(email);
}
@Test
void givenAccountInDb_whenPerformFindByUsernameInOrEmailIn_thenReturnsAccounts() {
List<String> emails = Arrays.asList("test@test.com", "abc@abc.com", "pqr@pqr.com");
List<String> usernames = Arrays.asList("user_editor", "user_admin");
List<Account> byUsernameInOrEmailIn = accountRepository.findByUsernameInOrEmailIn(usernames, emails);
assertThat(byUsernameInOrEmailIn.size()).isEqualTo(1);
assertThat(byUsernameInOrEmailIn.get(0)
.getEmail()).isEqualTo("test@test.com");
}
private Permission getPermissions() {
Permission editor = new Permission();
editor.setType("editor");
permissionRepository.save(editor);
return editor;
}
private void saveAccount() {
List<List<String>> sampleRecords = Arrays.asList(
Arrays.asList("test@test.com", "user_admin"),
Arrays.asList("test1@test.com", "user_admin_1"),
Arrays.asList("test2@test.com", "user_admin_2")
);
sampleRecords.forEach(sampleRecord -> {
Account account = new Account();
account.setEmail(sampleRecord.get(0));
account.setUsername(sampleRecord.get(1));
account.setPermission(getPermissions());
account.setPassword(UUID.randomUUID()
.toString());
account.setCreatedOn(Timestamp.from(Instant.now()));
account.setLastLogin(Timestamp.from(Instant.now()));
accountRepository.save(account);
System.out.println(account.toString());
});
}
}

View File

@ -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>

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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");
}
}

View File

@ -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;
}

View File

@ -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();
}

View File

@ -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);
}
}

View File

@ -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');

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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

View File

@ -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());
}
}

View File

@ -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>

View File

@ -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>

View File

@ -1167,7 +1167,7 @@
<hamcrest.version>2.2</hamcrest.version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<mockito.version>4.4.0</mockito.version>
<byte-buddy.version>1.14.6</byte-buddy.version>
<byte-buddy.version>1.14.11</byte-buddy.version>
<!-- logging -->
<!-- overwriting in the slf4j and logback in the hibernate-jpa, spring-data-eclipselink. When updated to the latest version remove the version from that module-->

View File

@ -10,9 +10,9 @@ public class GreetingServiceWithoutAOP {
private static final Logger logger = LoggerFactory.getLogger(GreetingServiceWithoutAOP.class);
public String greet(String name) {
logger.info(">> greet() - {}", name);
logger.debug(">> greet() - {}", name);
String result = String.format("Hello %s", name);
logger.info("<< greet() - {}", result);
logger.debug("<< greet() - {}", result);
return result;
}
}

View File

@ -28,13 +28,13 @@ public class LoggingAspect {
public void logBefore(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
String methodName = joinPoint.getSignature().getName();
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
}
@AfterReturning(value = "publicMethodsFromLoggingPackage()", returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
logger.info("<< {}() - {}", methodName, result);
logger.debug("<< {}() - {}", methodName, result);
}
@AfterThrowing(pointcut = "publicMethodsFromLoggingPackage()", throwing = "exception")
@ -47,9 +47,9 @@ public class LoggingAspect {
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
String methodName = joinPoint.getSignature().getName();
logger.info(">> {}() - {}", methodName, Arrays.toString(args));
logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
Object result = joinPoint.proceed();
logger.info("<< {}() - {}", methodName, result);
logger.debug("<< {}() - {}", methodName, result);
return result;
}
}

View File

@ -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>

View File

@ -0,0 +1,30 @@
package com.baeldung.returnnull;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;
public class GraphQLVoidScalar {
public static final GraphQLScalarType Void = GraphQLScalarType.newScalar()
.name("Void")
.description("A custom scalar that represents the null value")
.coercing(new Coercing() {
@Override
public Object serialize(Object dataFetcherResult) {
return null;
}
@Override
public Object parseValue(Object input) {
return null;
}
@Override
public Object parseLiteral(Object input) {
return null;
}
})
.build();
}

View File

@ -0,0 +1,14 @@
package com.baeldung.returnnull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.execution.RuntimeWiringConfigurer;
@Configuration
public class GraphQlConfig {
@Bean
public RuntimeWiringConfigurer runtimeWiringConfigurer() {
return wiringBuilder -> wiringBuilder.scalar(GraphQLVoidScalar.Void);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.returnnull;
public class Post {
private String id;
private String title;
private String text;
private String category;
private String author;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.returnnull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.stereotype.Controller;
@Controller
public class PostController {
List<Post> posts = new ArrayList<>();
@MutationMapping
public Void createPostReturnCustomScalar(@Argument String title, @Argument String text, @Argument String category, @Argument String author) {
Post post = new Post();
post.setId(UUID.randomUUID()
.toString());
post.setTitle(title);
post.setText(text);
post.setCategory(category);
post.setAuthor(author);
posts.add(post);
return null;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.returnnull;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReturnNullApp {
public static void main(String[] args) {
System.setProperty("spring.profiles.default", "returnnull");
SpringApplication.run(com.baeldung.chooseapi.ChooseApiApp.class, args);
}
}

View File

@ -0,0 +1,9 @@
server:
port: 8082
spring:
graphql:
graphiql:
enabled: true
schema:
locations: classpath:returnnull/

View File

@ -0,0 +1,18 @@
scalar Void
type Mutation {
createPostReturnNullableType(title: String!, text: String!, category: String!, author: String!) : Int
createPostReturnCustomScalar(title: String!, text: String!, category: String!, author: String!) : Void
}
type Post {
id: ID
title: String
text: String
category: String
author: String
}
type Query {
recentPosts(count: Int, offset: Int): [Post]!
}

View File

@ -0,0 +1,48 @@
package com.baeldung.returnnull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
import org.springframework.context.annotation.Import;
import org.springframework.graphql.test.tester.GraphQlTester;
import org.springframework.test.context.ActiveProfiles;
@GraphQlTest(PostController.class)
@ActiveProfiles("returnnull")
@Import(GraphQlConfig.class)
class PostControllerIntegrationTest {
@Autowired
private GraphQlTester graphQlTester;
@Test
void givenNewPostData_whenExecuteMutation_thenReturnCustomNullScalar() {
String documentName = "create_post_return_custom_scalar";
graphQlTester.documentName(documentName)
.variable("title", "New Post")
.variable("text", "New post text")
.variable("category", "category")
.variable("author", "Alex")
.execute()
.path("createPostReturnCustomScalar")
.valueIsNull();
}
@Test
void givenNewPostData_whenExecuteMutation_thenReturnNullType() {
String documentName = "create_post_return_nullable_type";
graphQlTester.documentName(documentName)
.variable("title", "New Post")
.variable("text", "New post text")
.variable("category", "category")
.variable("author", "Alex")
.execute()
.path("createPostReturnNullableType")
.valueIsNull();
}
}

View File

@ -0,0 +1,3 @@
mutation createPostReturnCustomScalar($title: String!, $text: String!, $category: String!, $author: String!) {
createPostReturnCustomScalar(title: $title, text: $text, category: $category, author: $author)
}

View File

@ -0,0 +1,3 @@
mutation createPostReturnNullableType($title: String!, $text: String!, $category: String!, $author: String!) {
createPostReturnNullableType(title: $title, text: $text, category: $category, author: $author)
}

View File

@ -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>

View File

@ -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>

View File

@ -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();

View File

@ -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;
}

View File

@ -9,9 +9,10 @@
<packaging>war</packaging>
<parent>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -42,6 +43,7 @@
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<classifier>jakarta</classifier>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@ -77,8 +79,19 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<ehcache.version>3.5.2</ehcache.version>
<caffeine.version>3.1.8</caffeine.version>
</properties>

View File

@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.io.Serializable;
import java.util.UUID;

View File

@ -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>

View File

@ -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();
}
}

View File

@ -10,9 +10,10 @@
<description>Spring Cloud Eureka Server and Sample Clients</description>
<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>
@ -23,6 +24,10 @@
<module>spring-cloud-eureka-server</module>
</modules>
<properties>
<spring-cloud-dependencies.version>2023.0.0</spring-cloud-dependencies.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -50,6 +50,18 @@
<groupId>io.undertow</groupId>
<artifactId>undertow-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-naming-client</artifactId>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-ejb-client</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.common</groupId>
<artifactId>wildfly-common</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -21,7 +21,7 @@ public class SpringEjbClientApplication {
Properties jndiProps = new Properties();
jndiProps.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put("jboss.naming.client.ejb.context", true);
jndiProps.put("java.naming.provider.url", "http-remoting://localhost:8080");
jndiProps.put("java.naming.provider.url", "remote+http://localhost:8080");
return new InitialContext(jndiProps);
}
@ -37,7 +37,7 @@ public class SpringEjbClientApplication {
@SuppressWarnings("rawtypes")
private String getFullName(Class classType) {
String moduleName = "spring-ejb-remote/";
String moduleName = "ejb:/spring-ejb-remote/";
String beanName = classType.getSimpleName();
String viewClassName = classType.getName();

View File

@ -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>

View File

@ -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

View File

@ -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" },

View File

@ -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 {

View File

@ -0,0 +1,56 @@
package com.baeldung.spring.kafka.kafkaexception;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import java.util.UUID;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.StringSerializer;
public class HandleInstanceAlreadyExistsException {
public static void generateUniqueClientIDUsingUUIDRandom() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
String clientId = "my-producer-" + UUID.randomUUID();
props.setProperty("client.id", clientId);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
clientId = "my-producer-" + UUID.randomUUID();
props.setProperty("client.id", clientId);
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
}
public static void closeProducerProperlyBeforeReinstantiate() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
producer1.close();
producer1 = new KafkaProducer<>(props);
}
public static void useUniqueObjectName() throws Exception {
MBeanServer mBeanServer1 = ManagementFactory.getPlatformMBeanServer();
MBeanServer mBeanServer2 = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName1 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric1");
ObjectName objectName2 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric2");
MyMBean mBean1 = new MyMBean();
mBeanServer1.registerMBean(mBean1, objectName1);
MyMBean mBean2 = new MyMBean();
mBeanServer2.registerMBean(mBean2, objectName2);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.spring.kafka.kafkaexception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KafkaAppMain {
public static void main(String[] args) {
SpringApplication.run(KafkaAppMain.class, args);
}
}

View File

@ -0,0 +1,123 @@
package com.baeldung.spring.kafka.kafkaexception;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.stereotype.Service;
@Service
public class SimulateInstanceAlreadyExistsException {
public static void jmxRegistrationConflicts() throws Exception {
// Create two instances of MBeanServer
MBeanServer mBeanServer1 = ManagementFactory.getPlatformMBeanServer();
MBeanServer mBeanServer2 = ManagementFactory.getPlatformMBeanServer();
// Define the same ObjectName for both MBeans
ObjectName objectName = new ObjectName("kafka.server:type=KafkaMetrics");
// Create and register the first MBean
MyMBean mBean1 = new MyMBean();
mBeanServer1.registerMBean(mBean1, objectName);
// Attempt to register the second MBean with the same ObjectName
MyMBean mBean2 = new MyMBean();
mBeanServer2.registerMBean(mBean2, objectName);
}
public static void duplicateConsumerClientID() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-consumer");
props.put("group.id", "test-group");
props.put("key.deserializer", StringDeserializer.class);
props.put("value.deserializer", StringDeserializer.class);
// Simulating concurrent client creation by multiple threads
for (int i = 0; i < 3; i++) {
new Thread(() -> {
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
}).start();
}
}
public void duplicateProducerClientID() throws Exception {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to create another producer using same client.id
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
}
public static void unclosedProducerAndReinitialize() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to reinitialize without proper close
producer1 = new KafkaProducer<>(props);
}
}
class MyMBean implements DynamicMBean {
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
}
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
return null;
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
MBeanOperationInfo[] operations = new MBeanOperationInfo[0];
MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];
return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications);
}
}

View File

@ -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>

View File

@ -10,7 +10,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<relativePath>../../parent-boot-3</relativePath>
<version>0.0.1-SNAPSHOT</version>
</parent>

View File

@ -15,10 +15,6 @@
</parent>
<dependencies>
<!--<dependency> -->
<!--<groupId>org.springframework.boot</groupId> -->
<!--<artifactId>spring-boot-starter-actuator</artifactId> -->
<!--</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>

View File

@ -7,6 +7,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@ -27,18 +28,13 @@ public class BasicAuthConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
http.csrf(AbstractHttpConfigurer::disable)
.cors(withDefaults())
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.antMatchers("/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/login").permitAll()
.anyRequest().authenticated())
.httpBasic(withDefaults());
return http.build();
}
}

View File

@ -3,7 +3,7 @@ package com.baeldung.springbootsecurityrest.controller;
import java.security.Principal;
import java.util.Base64;
import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -29,7 +30,7 @@
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@ -56,4 +57,7 @@
</plugins>
</build>
<properties>
<start-class>com.baeldung.manuallogout.ManualLogoutApplication</start-class>
</properties>
</project>

View File

@ -1,20 +1,20 @@
package com.baeldung.logoutredirects.securityconfig;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import jakarta.servlet.http.HttpServletResponse;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests(authz -> authz.mvcMatchers("/login")
http.authorizeHttpRequests(authz -> authz.requestMatchers("/login")
.permitAll()
.anyRequest()
.authenticated())

View File

@ -5,9 +5,6 @@ import static org.springframework.security.web.header.writers.ClearSiteDataHeade
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
@ -20,11 +17,14 @@ import org.springframework.security.web.authentication.logout.HeaderWriterLogout
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
@Configuration
@EnableWebSecurity
public class SimpleSecurityConfiguration {
private static Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class);
private static final Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class);
@Order(4)
@Configuration
@ -32,8 +32,8 @@ public class SimpleSecurityConfiguration {
@Bean
public SecurityFilterChain filterChainLogoutOnRequest(HttpSecurity http) throws Exception {
http.antMatcher("/request/**")
.authorizeRequests(authz -> authz.anyRequest()
http.securityMatcher("/request/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/request/logout")
.addLogoutHandler((request, response, auth) -> {
@ -53,8 +53,8 @@ public class SimpleSecurityConfiguration {
@Bean
public SecurityFilterChain filterChainDefaultLogout(HttpSecurity http) throws Exception {
http.antMatcher("/basic/**")
.authorizeRequests(authz -> authz.anyRequest()
http.securityMatcher("/basic/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/basic/basiclogout"));
return http.build();
@ -67,8 +67,8 @@ public class SimpleSecurityConfiguration {
@Bean
public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception {
http.antMatcher("/cookies/**")
.authorizeRequests(authz -> authz.anyRequest()
http.securityMatcher("/cookies/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/cookies/cookielogout")
.addLogoutHandler(new SecurityContextLogoutHandler())
@ -92,8 +92,8 @@ public class SimpleSecurityConfiguration {
@Bean
public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception {
http.antMatcher("/csd/**")
.authorizeRequests(authz -> authz.anyRequest()
http.securityMatcher("/csd/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/csd/csdlogout")
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE))));

View File

@ -9,9 +9,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -22,6 +19,9 @@ import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpSession;
@RunWith(SpringRunner.class)
@WebMvcTest(SimpleSecurityConfiguration.class)
public class ManualLogoutIntegrationTest {

View File

@ -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>

View File

@ -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 {

View File

@ -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();
}
}

View File

@ -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() {
}
}

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -26,11 +27,11 @@
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<artifactId>thymeleaf-spring6</artifactId>
</dependency>
<!-- Spring -->
<dependency>
@ -85,23 +86,24 @@
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<scope>runtime</scope>
</dependency>
<!-- http -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<!-- util -->
<dependency>

Some files were not shown because too many files have changed in this diff Show More