Merge branch 'master' into task/JAVA-26765

This commit is contained in:
Harry9656 2023-11-30 00:58:57 +01:00 committed by GitHub
commit f3e865d163
244 changed files with 3134 additions and 379 deletions

View File

@ -7,14 +7,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
public class CustomWebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@ -27,8 +27,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone")
@ -40,6 +40,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
return http.build();
}
@Bean

View File

@ -191,7 +191,7 @@
<bval.version>2.0.6</bval.version>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
<meecrowave-junit.version>1.2.15</meecrowave-junit.version>
<okhttp.version>3.10.0</okhttp.version>
<okhttp.version>4.12.0</okhttp.version>
<meecrowave-jpa.version>1.2.15</meecrowave-jpa.version>
<meecrowave-core.version>1.2.15</meecrowave-core.version>
<meecrowave-maven-plugin.version>1.2.15</meecrowave-maven-plugin.version>

View File

@ -9,3 +9,4 @@
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
- [Format Multiple or Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement)
- [Get All Record Fields and Its Values via Reflection](https://www.baeldung.com/java-reflection-record-fields-values)
- [Context-Specific Deserialization Filters in Java 17](https://www.baeldung.com/java-context-specific-deserialization-filters)

View File

@ -0,0 +1,47 @@
package com.baeldung.array.conversions;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertArrayEquals;
public class ByteToCharArrayUnitTest {
public static byte[] byteArray = {65, 66, 67, 68};
public static char[] expected = {'A', 'B', 'C', 'D'};
@Test
public void givenByteArray_WhenUsingStandardCharsets_thenConvertToCharArray() {
char[] charArray = new String(byteArray, StandardCharsets.UTF_8).toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingSUsingStreams_thenConvertToCharArray() throws IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
InputStreamReader reader = new InputStreamReader(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int data;
while ((data = reader.read()) != -1) {
char ch = (char) data;
outputStream.write(ch);
}
char[] charArray = outputStream.toString().toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingCharBuffer_thenConvertToCharArray() {
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
char[] charArray = new char[charBuffer.remaining()];
charBuffer.get(charArray);
assertArrayEquals(expected, charArray);
}
}

View File

@ -10,4 +10,5 @@
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)

View File

@ -4,4 +4,5 @@
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-max-size)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)

View File

@ -38,6 +38,16 @@
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.37</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.37</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,25 @@
package com.baeldung.map;
import java.util.HashMap;
public class HashMapWithMaxSizeLimit<K, V> extends HashMap<K, V> {
private int maxSize = -1;
public HashMapWithMaxSizeLimit() {
super();
}
public HashMapWithMaxSizeLimit(int maxSize) {
super();
this.maxSize = maxSize;
}
@Override
public V put(K key, V value) {
if (this.maxSize == -1 || this.containsKey(key) || this.size() < this.maxSize) {
return super.put(key, value);
}
throw new RuntimeException("Max size exceeded!");
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.map.incrementmapkey;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class BenchmarkMapMethodsJMH {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkGuavaMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingAtomicMap(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchContainsKeyMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingContainsKey(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkComputeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingCompute(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkMergeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingMerge(getString());
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
private String getString() {
return
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
+ "\n"
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.map;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class LimitMaxSizeHashMapByCustomHashMapUnitTest {
private final int MAX_SIZE = 4;
private HashMapWithMaxSizeLimit<Integer, String> hashMapWithMaxSizeLimit;
@Test
void givenCustomHashMapObject_whenThereIsNoLimit_thenDoesNotThrowException() {
hashMapWithMaxSizeLimit = new HashMapWithMaxSizeLimit<Integer, String>();
assertDoesNotThrow(() -> {
for (int i = 0; i < 10000; i++) {
hashMapWithMaxSizeLimit.put(i, i + "");
}
});
}
@Test
void givenCustomHashMapObject_whenLimitNotReached_thenDoesNotThrowException() {
hashMapWithMaxSizeLimit = new HashMapWithMaxSizeLimit<Integer, String>(MAX_SIZE);
assertDoesNotThrow(() -> {
for (int i = 0; i < 4; i++) {
hashMapWithMaxSizeLimit.put(i, i + "");
}
});
}
@Test
void givenCustomHashMapObject_whenReplacingValueWhenLimitIsReached_thenDoesNotThrowException() {
hashMapWithMaxSizeLimit = new HashMapWithMaxSizeLimit<Integer, String>(MAX_SIZE);
assertDoesNotThrow(() -> {
hashMapWithMaxSizeLimit.put(1, "One");
hashMapWithMaxSizeLimit.put(2, "Two");
hashMapWithMaxSizeLimit.put(3, "Three");
hashMapWithMaxSizeLimit.put(4, "Four");
hashMapWithMaxSizeLimit.put(4, "4");
});
}
@Test
void givenCustomHashMapObject_whenLimitExceeded_thenThrowsException() {
hashMapWithMaxSizeLimit = new HashMapWithMaxSizeLimit<Integer, String>(MAX_SIZE);
Exception exception = assertThrows(RuntimeException.class, () -> {
for (int i = 0; i < 5; i++) {
hashMapWithMaxSizeLimit.put(i, i + "");
}
});
String messageThrownWhenSizeExceedsLimit = "Max size exceeded!";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.equals(messageThrownWhenSizeExceedsLimit));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class LimitMaxSizeHashMapByLinkedHashMapUnitTest {
@Test
void givenLinkedHashMapObject_whenAddingNewEntry_thenEldestEntryIsRemoved() {
final int MAX_SIZE = 4;
LinkedHashMap<Integer, String> linkedHashMap;
linkedHashMap = new LinkedHashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
return size() > MAX_SIZE;
}
};
linkedHashMap.put(1, "One");
linkedHashMap.put(2, "Two");
linkedHashMap.put(3, "Three");
linkedHashMap.put(4, "Four");
linkedHashMap.put(5, "Five");
String[] expectedArrayAfterFive = { "Two", "Three", "Four", "Five" };
assertArrayEquals(expectedArrayAfterFive, linkedHashMap.values()
.toArray());
linkedHashMap.put(6, "Six");
String[] expectedArrayAfterSix = { "Three", "Four", "Five", "Six" };
assertArrayEquals(expectedArrayAfterSix, linkedHashMap.values()
.toArray());
}
}

View File

@ -0,0 +1,141 @@
package com.baeldung.map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.Test;
class Player {
private String name;
private Integer score = 0;
public Player(String name, Integer score) {
this.name = name;
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Player)) {
return false;
}
Player player = (Player) o;
if (!Objects.equals(name, player.name)) {
return false;
}
return Objects.equals(score, player.score);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (score != null ? score.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public class LinkedHashMapSortByValueUnitTest {
private static LinkedHashMap<String, Integer> MY_MAP = new LinkedHashMap<>();
static {
MY_MAP.put("key a", 4);
MY_MAP.put("key b", 1);
MY_MAP.put("key c", 3);
MY_MAP.put("key d", 2);
MY_MAP.put("key e", 5);
}
private static LinkedHashMap<String, Integer> EXPECTED_MY_MAP = new LinkedHashMap<>();
static {
EXPECTED_MY_MAP.put("key b", 1);
EXPECTED_MY_MAP.put("key d", 2);
EXPECTED_MY_MAP.put("key c", 3);
EXPECTED_MY_MAP.put("key a", 4);
EXPECTED_MY_MAP.put("key e", 5);
}
private static final LinkedHashMap<String, Player> PLAYERS = new LinkedHashMap<>();
static {
PLAYERS.put("player a", new Player("Eric", 9));
PLAYERS.put("player b", new Player("Kai", 7));
PLAYERS.put("player c", new Player("Amanda", 20));
PLAYERS.put("player d", new Player("Kevin", 4));
}
private static final LinkedHashMap<String, Player> EXPECTED_PLAYERS = new LinkedHashMap<>();
static {
EXPECTED_PLAYERS.put("player d", new Player("Kevin", 4));
EXPECTED_PLAYERS.put("player b", new Player("Kai", 7));
EXPECTED_PLAYERS.put("player a", new Player("Eric", 9));
EXPECTED_PLAYERS.put("player c", new Player("Amanda", 20));
}
@Test
void whenUsingCollectionSort_thenGetExpectedResult() {
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(MY_MAP.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue()
.compareTo(o2.getValue());
}
});
LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> e : entryList) {
result.put(e.getKey(), e.getValue());
}
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndFillAMap_thenGetExpectedResult() {
LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
MY_MAP.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue()));
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndCollect_thenGetExpectedResult() {
LinkedHashMap<String, Integer> result = MY_MAP.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);
assertEquals(EXPECTED_MY_MAP, result);
}
@Test
void whenUsingEntrycomparingByValueAndComparator_thenGetExpectedResult() {
LinkedHashMap<String, Player> result = PLAYERS.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.comparing(Player::getScore)))
.collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);
assertEquals(EXPECTED_PLAYERS, result);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.map;
package com.baeldung.map.incrementmapkey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -9,6 +9,8 @@ import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.map.incrementmapkey.IncrementMapValueWays;
public class IncrementMapValueUnitTest {
@Test

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)

View File

@ -2,7 +2,7 @@ package com.baeldung.wait_synchronization;
public class ConditionChecker {
private volatile Boolean jobIsDone;
private volatile boolean jobIsDone;
private final Object lock = new Object();
public void ensureCondition() {
@ -21,4 +21,4 @@ public class ConditionChecker {
lock.notify();
}
}
}
}

View File

@ -159,7 +159,7 @@
</profiles>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<ascii.version>0.3.2</ascii.version>

View File

@ -10,3 +10,4 @@ This module contains articles about converting between Java date and time object
- [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime)
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)

View File

@ -33,7 +33,7 @@
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>

View File

@ -61,7 +61,7 @@
</build>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<wiremock.version>3.3.1</wiremock.version>
</properties>

View File

@ -12,6 +12,10 @@ public class WriteCsvFileExample {
}
public String escapeSpecialCharacters(String data) {
if (data == null) {
throw new IllegalArgumentException("Input data cannot be null");
}
String escapedData = data.replaceAll("\\R", " ");
if (data.contains(",") || data.contains("\"") || data.contains("'")) {
data = data.replace("\"", "\"\"");

View File

@ -134,7 +134,7 @@
<properties>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.5.0</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<hsqldb.version>2.7.1</hsqldb.version>
<!-- Mime Type Libraries -->
<tika.version>2.8.0</tika.version>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-ipc</artifactId>
<name>core-java-ipc</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchKey;
import java.nio.file.WatchEvent;
import java.nio.file.WatchService;
public class DirectoryLiveTest {
@Test
public void consumer() throws Exception {
WatchService watchService = FileSystems.getDefault().newWatchService();
// Set this to an appropriate directory.
Path path = Paths.get("/tmp/ipc");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
// React to new file.
System.out.println(event);
}
key.reset();
}
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
public class JmxLiveTest {
/*
* This test needs to be run with the following system properties defined:
* -Dcom.sun.management.jmxremote=true
* -Dcom.sun.management.jmxremote.port=1234
* -Dcom.sun.management.jmxremote.authenticate=false
* -Dcom.sun.management.jmxremote.ssl=false
*/
@Test
public void consumer() throws Exception {
ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test");
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.registerMBean(new IPCTest(), objectName);
TimeUnit.MINUTES.sleep(50);
}
@Test
public void producer() throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi");
try (JMXConnector jmxc = JMXConnectorFactory.connect(url, null)) {
ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test");
IPCTestMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(), objectName, IPCTestMBean.class, true);
mbeanProxy.sendMessage("Hello");
}
}
public interface IPCTestMBean {
void sendMessage(String message);
}
class IPCTest implements IPCTestMBean {
@Override
public void sendMessage(String message) {
System.out.println("Received message: " + message);
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.ipc;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketsLiveTest {
@Test
public void consumer() throws Exception {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received message: " + line);
}
}
}
@Test
public void producer() throws Exception {
try (Socket clientSocket = new Socket("localhost", 1234)) {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out.println("Hello");
String response = in.readLine();
}
}
}

View File

@ -274,7 +274,7 @@
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<maven-assembly-plugin.version>3.3.0</maven-assembly-plugin.version>

View File

@ -0,0 +1,16 @@
package com.baeldung.returnfirstnonnull;
class LazyEvaluate {
String methodA() {
return null;
}
String methodB() {
return "first non null";
}
String methodC() {
return "second non null";
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.returnfirstnonempty;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ReturnFirstNonEmptyOptionalUnitTest {
private List<Optional<String>> optionals;
@BeforeEach
public void init() {
optionals = Arrays.asList(Optional.<String> empty(), Optional.of("first non empty"), Optional.of("second non empty"));
}
@Test
void givenListOfOptionals_whenStreaming_thenReturnFirstNonEmpty() {
Optional<String> object = optionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertThat(object).contains("first non empty");
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.returnfirstnonnull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class ReturnFirstNonNullLazyEvaluateUnitTest {
private final LazyEvaluate spy = Mockito.spy(new LazyEvaluate());
@Test
void givenChainOfMethods_whenUsingIfStatements_thenLazilyEvaluateMethodsUntilFirstNonNull() {
String object = spy.methodA();
if (object == null) {
object = spy.methodB();
}
if (object == null) {
object = spy.methodC();
}
assertEquals("first non null", object);
verify(spy, times(1)).methodA();
verify(spy, times(1)).methodB();
verify(spy, times(0)).methodC();
}
@Test
void givenChainOfMethods_whenUsingApacheCommonsLang3_thenReturnFirstNonNull() {
String object = ObjectUtils.getFirstNonNull(spy::methodA, spy::methodB, spy::methodC);
assertEquals("first non null", object);
verify(spy, times(1)).methodA();
verify(spy, times(1)).methodB();
verify(spy, times(0)).methodC();
}
@Test
void givenChainOfMethods_whenUsingSupplierInterface_thenLazilyEvaluateMethodsUntilFirstNonNull() {
Optional<String> object = Stream.<Supplier<String>> of(spy::methodA, spy::methodB, spy::methodC)
.map(Supplier::get)
.filter(Objects::nonNull)
.findFirst();
assertThat(object).contains("first non null");
verify(spy, times(1)).methodA();
verify(spy, times(1)).methodB();
verify(spy, times(0)).methodC();
}
@Test
void givenNonNullObjectAndFallbackMethod_whenUsingApacheCommonsLang3_thenReturnFirstNonNull() {
String nonNullObject = spy.methodB();
String object = ObjectUtils.getIfNull(nonNullObject, spy::methodC);
assertEquals("first non null", object);
verify(spy, times(0)).methodC();
}
@Test
void givenNullObjectAndFallbackMethod_whenUsingApacheCommonsLang3_thenReturnFirstNonNull() {
String nullObject = null;
String object = ObjectUtils.getIfNull(nullObject, spy::methodB);
assertEquals("first non null", object);
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.returnfirstnonnull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.lang3.ObjectUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
public class ReturnFirstNonNullUnitTest {
private List<String> objects;
@BeforeEach
public void init() {
objects = Arrays.asList(null, "first non null", "second nun null");
}
@Test
void givenListOfObjects_whenFilterIsLambdaNullCheckInStream_thenReturnFirstNonNull() {
Optional<String> object = objects.stream()
.filter(o -> o != null)
.findFirst();
assertThat(object).contains("first non null");
}
@Test
void givenListOfObjects_whenFilterIsMethodRefNullCheckInStream_thenReturnFirstNonNull() {
Optional<String> object = objects.stream()
.filter(Objects::nonNull)
.findFirst();
assertThat(object).contains("first non null");
}
@Test
void givenListOfObjects_whenIteratingWithForLoop_thenReturnFirstNonNull() {
String object = null;
for (int i = 0; i < objects.size(); i++) {
if (objects.get(i) != null) {
object = objects.get(i);
break;
}
}
assertEquals("first non null", object);
}
@Test
void givenListOfObjects_whenUsingApacheCommonsLang3_thenReturnFirstNonNull() {
String object = ObjectUtils.firstNonNull(objects.toArray(new String[0]));
assertEquals("first non null", object);
}
@Test
void givenListOfObjects_whenUsingGoogleGuavaIterables_thenReturnFirstNonNull() {
String object = Iterables.find(objects, Predicates.notNull());
assertEquals("first non null", object);
}
@Test
void givenTwoObjects_whenUsingGoogleGuavaMoreObjects_thenReturnFirstNonNull() {
String nullObject = null;
String nonNullObject = "first non null";
String object = MoreObjects.firstNonNull(nullObject, nonNullObject);
assertEquals("first non null", object);
}
}

View File

@ -26,13 +26,25 @@ public class Rectangle {
this.topRight = topRight;
}
public boolean isOverlapping(Rectangle other) {
// one rectangle is to the top of the other
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
public boolean isOverlapping(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() < comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() > comparedRectangle.topRight.getY()) {
return false;
}
// one rectangle is to the left of the other
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() < comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() > comparedRectangle.topRight.getX()) {
return false;
}
return true;
}
public boolean isOverlappingWithoutBorders(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() <= comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() >= comparedRectangle.topRight.getY()) {
return false;
}
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() <= comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() >= comparedRectangle.topRight.getX()) {
return false;
}
return true;

View File

@ -1,7 +1,8 @@
package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class RectangleUnitTest {
@ -36,4 +37,18 @@ public class RectangleUnitTest {
assertFalse(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingCalled_shouldReturnTrue() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertTrue(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingWithoutBordersCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertFalse(rectangle1.isOverlappingWithoutBorders(rectangle2));
}
}

View File

@ -35,7 +35,7 @@
<properties>
<commons-lang.version>2.6</commons-lang.version>
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version>
<equalsverifier.version>3.15.3</equalsverifier.version>
</properties>
</project>

View File

@ -10,3 +10,4 @@ This module contains articles about types in Java
- [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list)
- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum)
- [Implementing toString() on enums in Java](https://www.baeldung.com/java-enums-tostring)
- [Checking if an Objects Type Is Enum](https://www.baeldung.com/java-check-object-enum)

View File

@ -0,0 +1,75 @@
package com.baeldung.enums.classcheck;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
enum Device {
Keyboard, Monitor, Mouse, Printer
}
enum Weekday {
Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday {
@Override
boolean isWeekend() {
return true;
}
},
Sunday {
@Override
boolean isWeekend() {
return true;
}
};
boolean isWeekend() {
return false;
}
}
public class CheckClassIsEnumUnitTest {
@Test
void whenUsingInstanceOf_thenGetExpectedResult() {
Object obj = Device.Keyboard;
assertTrue(obj instanceof Enum);
}
@Test
void whenUsingisInstance_thenGetExpectedResult() {
Object obj = Device.Keyboard;
assertTrue(Enum.class.isInstance(obj));
}
@Test
void whenUsingEnumClassisAssignableFrom_thenGetExpectedResult() {
Object obj = Device.Keyboard;
assertTrue(Enum.class.isAssignableFrom(obj.getClass()));
}
@Test
void whenUsingGetClassIsEnum_thenGetExpectedResult() {
assertTrue(Device.class.isEnum());
Object obj = Device.Keyboard;
assertTrue(obj.getClass().isEnum());
}
@Test
void whenEnum_thenGetExpectedResult() {
Object monday = Weekday.Monday;
assertTrue(monday instanceof Enum);
assertTrue(Enum.class.isInstance(monday));
assertTrue(Enum.class.isAssignableFrom(monday.getClass()));
assertTrue(monday.getClass().isEnum());
Object sunday = Weekday.Sunday;
assertTrue(sunday instanceof Enum);
assertTrue(Enum.class.isInstance(sunday));
assertTrue(Enum.class.isAssignableFrom(sunday.getClass()));
assertFalse(sunday.getClass().isEnum()); // <-- isEnum() check failed when Enum values with body
}
}

View File

@ -56,7 +56,7 @@
<properties>
<apache.commons-validator.version>1.7</apache.commons-validator.version>
<jsoup.version>1.15.4</jsoup.version>
<jsoup.version>1.16.2</jsoup.version>
</properties>
</project>

View File

@ -0,0 +1,69 @@
package com.baeldung.negate;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.*;
public class NegateIntUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class);
@Test
void whenUsingUnaryMinusOperator_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, -x);
int z = 0;
assertEquals(0, -z);
int n = -42;
assertEquals(42, -n);
}
@Test
void whenUsingBitwiseComplementOperator_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, ~x + 1);
int z = 0;
assertEquals(0, ~z + 1);
int n = -42;
assertEquals(42, ~n + 1);
}
@Test
void givenIntMinValue_whenUsingUnaryMinusOperator_thenCannotGetExpectedResult() {
int min = Integer.MIN_VALUE;
LOG.info("The value of '-min' is: " + -min);
assertTrue((-min) < 0);
}
@Test
void givenIntMinValue_whenUsingBitwiseComplementOperator_thenCannotGetExpectedResult() {
int min = Integer.MIN_VALUE;
int result = ~min + 1;
LOG.info("The value of '~min + 1' is: " + result);
assertTrue(result < 0);
}
@Test
void whenUsingUnaryMinusOperatorWithMinInt_thenGetExpectedResult() {
int x = 42;
assertEquals(-42, Math.negateExact(x));
int z = 0;
assertEquals(0, Math.negateExact(z));
int n = -42;
assertEquals(42, Math.negateExact(n));
int min = Integer.MIN_VALUE;
assertThrowsExactly(ArithmeticException.class, () -> Math.negateExact(min));
}
}

View File

@ -177,7 +177,7 @@
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
<spring.core.version>4.3.20.RELEASE</spring.core.version>
</properties>

View File

@ -5,3 +5,4 @@
- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters)
- [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string)
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank)

View File

@ -24,12 +24,6 @@
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@ -39,7 +33,7 @@
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.9.1</version>
<version>${liquibase.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -67,6 +61,7 @@
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
<commons-text.version>1.10.0</commons-text.version>
<liquibase.core.version>4.25.0</liquibase.core.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.centertext;
import liquibase.repackaged.org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

View File

@ -0,0 +1,25 @@
package com.baeldung.isemptyvsisblank;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class StringIsEmptyVsIsBlankUnitTest {
@Test
public void givenString_whenCallIsEmpty_thenReturnCorrectValues() {
assertFalse("Example text".isEmpty());
assertTrue("".isEmpty());
assertFalse(" ".isEmpty());
assertFalse("\t\n\r\f".isEmpty());
}
@Test
public void givenString_whenCallStringIsBlank_thenReturnCorrectValues() {
assertFalse("Example text".isBlank());
assertTrue("".isBlank());
assertTrue(" ".isBlank());
assertTrue("\t\n\r\f ".isBlank());
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.stringbuffer;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 10000, iterations = 10)
@Warmup(batchSize = 1000, iterations = 10)
@State(Scope.Thread)
public class ComparePerformance {
String strInitial = "springframework";
String strFinal = "";
String replacement = "java-";
@Benchmark
public String benchmarkStringConcatenation() {
strFinal += strInitial;
return strFinal;
}
@Benchmark
public StringBuffer benchmarkStringBufferConcatenation() {
StringBuffer stringBuffer = new StringBuffer(strFinal);
stringBuffer.append(strInitial);
return stringBuffer;
}
@Benchmark
public String benchmarkStringReplacement() {
strFinal = strInitial.replaceFirst("spring", replacement);
return strFinal;
}
@Benchmark
public StringBuffer benchmarkStringBufferReplacement() {
StringBuffer stringBuffer = new StringBuffer(strInitial);
stringBuffer.replace(0,6, replacement);
return stringBuffer;
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(ComparePerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringbuffer;
public class HashCode {
public static long getHashCodeString(String string) {
return string.hashCode();
}
public static long getHashCodeSBuffer(StringBuffer strBuff) {
return strBuff.hashCode();
}
public static void main(String[] args) {
String str = "Spring";
System.out.println("String HashCode pre concatenation :" + getHashCodeString(str));
str += "Framework";
System.out.println("String HashCode post concatenation :" + getHashCodeString(str));
StringBuffer sBuf = new StringBuffer("Spring");
System.out.println("StringBuffer HashCode pre concatenation :" + getHashCodeSBuffer(sBuf));
sBuf.append("Framework");
System.out.println("StringBuffer HashCode post concatenation :" + getHashCodeSBuffer(sBuf));
}
}

View File

@ -17,7 +17,7 @@ public class StringIteratorTest {
public void whenUseJavaForLoop_thenIterate() {
String input = "Hello, Baeldung!";
String expectedOutput = "Hello, Baeldung!";
String result = StringIterator.javaForLoop(input);
String result = StringIterator.javaforLoop(input);
assertEquals(expectedOutput, result);
}
@ -25,7 +25,7 @@ public class StringIteratorTest {
public void whenUseForEachMethod_thenIterate() {
String input = "Hello, Baeldung!";
String expectedOutput = "Hello, Baeldung!";
String result = StringIterator.java8ForEach(input);
String result = StringIterator.java8forEach(input);
assertEquals(expectedOutput, result);
}

View File

@ -0,0 +1,32 @@
package com.baeldung.stringbuffer;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparePerformanceTest {
ComparePerformance cp = new ComparePerformance();
@Test
public void whenStringConcatenated_thenResultAsExpected() {
assertThat(cp.benchmarkStringConcatenation()).isEqualTo("springframework");
}
@Test
public void whenStringBufferConcatenated_thenResultAsExpected() {
StringBuffer stringBuffer = new StringBuffer("springframework");
assertThat(cp.benchmarkStringBufferConcatenation()).isEqualToIgnoringCase(stringBuffer);
}
@Test
public void whenStringReplaced_thenResultAsExpected() {
assertThat(cp.benchmarkStringReplacement()).isEqualTo("java-framework");
}
@Test
public void whenStringBufferReplaced_thenResultAsExpected() {
StringBuffer stringBuffer = new StringBuffer("java-framework");
assertThat(cp.benchmarkStringBufferReplacement()).isEqualToIgnoringCase(stringBuffer);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringbuffer;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HashCodeTest {
String str = "Spring";
StringBuffer sBuf = new StringBuffer("Spring");
@Test
public void whenStringConcat_thenHashCodeChanges() {
HashCode hc = new HashCode();
long initialStringHashCode = hc.getHashCodeString(str);
long initialSBufHashCode = hc.getHashCodeSBuffer(sBuf);
str += "Framework";
sBuf.append("Framework");
assertThat(initialStringHashCode).isNotEqualTo(hc.getHashCodeString(str));
assertThat(initialSBufHashCode).isEqualTo(hc.getHashCodeSBuffer(sBuf));
}
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-string-swing</artifactId>
<name>core-java-string-swing</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.customfont;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class CustomFonts {
public static void main(String[] args) {
usingCustomFonts();
}
public static void usingCustomFonts() {
final GraphicsEnvironment GE = GraphicsEnvironment.getLocalGraphicsEnvironment();
final List<String> AVAILABLE_FONT_FAMILY_NAMES = Arrays.asList(GE.getAvailableFontFamilyNames());
try {
final List<File> LIST = Arrays.asList(
new File("font/JetBrainsMono/JetBrainsMono-Thin.ttf"),
new File("font/JetBrainsMono/JetBrainsMono-Light.ttf"),
new File("font/Roboto/Roboto-Light.ttf"),
new File("font/Roboto/Roboto-Regular.ttf"),
new File("font/Roboto/Roboto-Medium.ttf")
);
for (File LIST_ITEM : LIST) {
if (LIST_ITEM.exists()) {
Font FONT = Font.createFont(Font.TRUETYPE_FONT, LIST_ITEM);
if (!AVAILABLE_FONT_FAMILY_NAMES.contains(FONT.getFontName())) {
GE.registerFont(FONT);
}
}
}
} catch (FontFormatException | IOException exception) {
JOptionPane.showMessageDialog(null, exception.getMessage());
}
JFrame frame = new JFrame("Custom Font Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JLabel label1 = new JLabel("TEXT1");
label1.setFont(new Font("Roboto Medium", Font.PLAIN, 17));
JLabel label2 = new JLabel("TEXT2");
label2.setFont(new Font("JetBrainsMono-Thin", Font.PLAIN, 17));
frame.add(label1);
frame.add(label2);
frame.pack();
frame.setVisible(true);
}
}

View File

@ -154,7 +154,7 @@
</profiles>
<properties>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,83 @@
package com.baeldung.uuid;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;
/**
* Methods are called by reflection in the unit test
*/
@SuppressWarnings("unused")
public class UUIDPositiveLongGenerator {
public long getLeastSignificantBits() {
return Math.abs(UUID.randomUUID().getLeastSignificantBits());
}
public long getMostSignificantBits() {
return Math.abs(UUID.randomUUID().getMostSignificantBits());
}
public long combineByteBuffer() {
UUID uuid = UUID.randomUUID();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
bb.rewind();
return Math.abs(bb.getLong());
}
public long combineBitwise() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineDirect() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1));
}
public long combinePermutation() {
UUID uuid = UUID.randomUUID();
long mostSigBits = uuid.getMostSignificantBits();
long leastSigBits = uuid.getLeastSignificantBits();
byte[] uuidBytes = new byte[16];
for (int i = 0; i < 8; i++) {
uuidBytes[i] = (byte) (mostSigBits >>> (8 * (7 - i)));
uuidBytes[i + 8] = (byte) (leastSigBits >>> (8 * (7 - i)));
}
long result = 0;
for (byte b : uuidBytes) {
result = (result << 8) | (b & 0xFF);
}
return Math.abs(result);
}
public long combineWithSecureRandom() {
UUID uniqueUUID = UUID.randomUUID();
SecureRandom secureRandom = new SecureRandom();
long randomBits = secureRandom.nextLong();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ randomBits;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineWithNanoTime() {
UUID uniqueUUID = UUID.randomUUID();
long nanoTime = System.nanoTime();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ nanoTime;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class UUIDPositiveLongGeneratorUnitTest {
private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator();
private final Set<Long> uniqueValues = new HashSet<>();
@Test
void whenForeachMethods_thenRetryWhileNotUnique() throws Exception {
for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) {
long uniqueValue;
do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue));
assertThat(uniqueValue).isPositive();
}
}
@Test
void whenGivenLongValue_thenCheckUniqueness() {
long uniqueValue = generateUniqueLong();
assertThat(uniqueValue).isPositive();
}
private long generateUniqueLong() {
long uniqueValue;
do uniqueValue = uuidLongGenerator.combineBitwise(); while (!isUnique(uniqueValue));
return uniqueValue;
}
private boolean isUnique(long value) {
// Implement uniqueness checking logic, for example, by checking in the database
return uniqueValues.add(value);
}
}

View File

@ -2,8 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

View File

@ -54,6 +54,7 @@
<module>core-java-concurrency-simple</module>
<module>core-java-datetime-string</module>
<module>core-java-io-conversions-2</module>
<module>core-java-ipc</module>
<module>core-java-jpms</module>
<module>core-java-lang-oop-constructors-2</module>
<module>core-java-methods</module>
@ -183,6 +184,7 @@
<module>core-java-string-algorithms</module>
<module>core-java-string-algorithms-2</module>
<module>core-java-string-apis</module>
<module>core-java-swing</module>
<module>core-java-string-apis-2</module>
<module>core-java-string-conversions</module>
<module>core-java-string-conversions-2</module>
@ -198,7 +200,8 @@
<module>core-java-records</module>
<module>core-java-9-jigsaw</module>
<!--<module>core-java-20</module>--> <!--JAVA-25373-->
<!--<module>core-java-conditionals</module>--> <!--JAVA-25373-->
<!--<module>core-java-21</module>--> <!--JAVA-25373-->
<!--<module>core-java-conditionals</module>--> <!--JAVA-20931-->
<module>core-java-collections-set</module>
<module>core-java-date-operations-1</module>
<module>core-java-datetime-conversion</module>

View File

@ -74,6 +74,17 @@
<version>${wire.mock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
@ -85,7 +96,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.5.0</version>
<version>3.1.0</version>
<executions>
<execution>
<id>xjc</id>
@ -131,6 +142,7 @@
<feign.form.spring.version>3.8.0</feign.form.spring.version>
<spring.cloud.openfeign.version>3.1.2</spring.cloud.openfeign.version>
<wire.mock.version>2.33.2</wire.mock.version>
<jakarta.xml.bind.version>4.0.0</jakarta.xml.bind.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

View File

@ -0,0 +1,20 @@
plugins {
id 'java'
}
group = 'org.baeldung'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.9.1')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation 'io.micrometer:micrometer-core:1.12.0'
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,12 @@
# HTTP proxy settings
systemProp.http.proxyHost=localhost
systemProp.http.proxyPort=3128
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.http.nonProxyHosts=*.nonproxyrepos.com
# HTTPS proxy settings
systemProp.https.proxyHost=localhost
systemProp.https.proxyPort=3128
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD
systemProp.https.nonProxyHosts=*.nonproxyrepos.com

View File

@ -0,0 +1,6 @@
#Thu Nov 16 23:15:01 GMT 2023
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,2 @@
rootProject.name = 'gradle-proxy-configuration'

View File

@ -65,7 +65,7 @@
<properties>
<exchange-rate-api.version>1.0.0-SNAPSHOT</exchange-rate-api.version>
<okhttp.version>3.10.0</okhttp.version>
<okhttp.version>4.12.0</okhttp.version>
<javax.json.bind-api.version>1.0</javax.json.bind-api.version>
<yasson.version>1.0.1</yasson.version>
<javax.json.version>1.1.2</javax.json.version>

View File

@ -9,26 +9,24 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>
@ -42,9 +40,16 @@
<!--<version>${hibernate-validator.ap.version}</version> </path> </annotationProcessorPaths> </configuration> -->
<!--</plugin> </plugins> </build> -->
<properties>
<spring.boot.version>3.0.4</spring.boot.version>
<jackson.databind.version>2.14.0</jackson.databind.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.javaxval;
package com.baeldung.javaxval.afterdeserialization;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

View File

@ -8,20 +8,19 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -38,7 +37,6 @@
<properties>
<hibernate-validator.ap.version>8.0.1.Final</hibernate-validator.ap.version>
<spring.boot.version>3.0.4</spring.boot.version>
</properties>
</project>

View File

@ -1,52 +1,44 @@
package com.baeldung.configuration;
import java.util.HashSet;
import java.util.Set;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
public class WebSecurityConfiguration {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.inMemoryAuthentication()
.withUser("admin").password(encoder.encode("admin")).roles("USER", "ADMIN")
.and()
.withUser("user1").password(encoder.encode("password1")).roles("USER")
.and()
.withUser("user2").password(encoder.encode("password2")).roles("USER")
.and()
.withUser("user3").password(encoder.encode("password3")).roles("USER")
.and()
.withUser("user4").password(encoder.encode("password4")).roles("USER")
.and()
.withUser("user5").password(encoder.encode("password5")).roles("USER")
.and()
.withUser("user6").password(encoder.encode("password6")).roles("USER")
.and()
.withUser("user7").password(encoder.encode("password7")).roles("USER")
.and()
.withUser("user8").password(encoder.encode("password8")).roles("USER")
.and()
.withUser("user9").password(encoder.encode("password9")).roles("USER")
.and()
.withUser("user10").password(encoder.encode("password10")).roles("USER");
Set<UserDetails> users = new HashSet<>();
users.add(User.withUsername("admin").password(encoder.encode("admin")).roles("USER", "ADMIN").build());
for(int i=1;i<=10;i++){
users.add(User.withUsername("user"+i).password(encoder.encode("password")+i).roles("USER").build());
}
return new InMemoryUserDetailsManager(users);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();
return http.build();
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.gson.multiplefields;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
public class BasicStudent {
private String name;
private transient String major;
@SerializedName("major")
private String concentration;
public BasicStudent() {
}
public BasicStudent(String name, String major, String concentration) {
this.name = name;
this.major = major;
this.concentration = concentration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof BasicStudent))
return false;
BasicStudent student = (BasicStudent) o;
return Objects.equals(name, student.name) && Objects.equals(major, student.major) && Objects.equals(concentration, student.concentration);
}
@Override
public int hashCode() {
return Objects.hash(name, major, concentration);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getConcentration() {
return concentration;
}
public void setConcentration(String concentration) {
this.concentration = concentration;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.gson.multiplefields;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class StudentExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes field) {
// Ignore all field values from V1 type
return field.getDeclaringClass() == StudentV1.class;
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.gson.multiplefields;
public class StudentV1 {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// Default constructor for Gson
public StudentV1() {
}
public StudentV1(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.gson.multiplefields;
import java.util.Objects;
import com.google.gson.annotations.Expose;
public class StudentV2 extends StudentV1 {
@Expose
private String firstName;
@Expose
private String lastName;
@Expose
private String major;
@Override
public String getFirstName() {
return firstName;
}
@Override
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
// Default constructor for Gson
public StudentV2() {
}
public StudentV2(String firstName, String lastName, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StudentV2))
return false;
StudentV2 studentV2 = (StudentV2) o;
return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, major);
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.gson.multiplefields;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonMultipleFieldsUnitTest {
@Test
public void givenBasicStudent_whenSerializingWithGson_thenTransientFieldNotSet() {
// Given a class with a transient field
BasicStudent student = new BasicStudent("Henry Winter", "Greek Studies", "Classical Greek Studies");
// When serializing using Gson
Gson gson = new Gson();
String json = gson.toJson(student);
// Then the deserialized instance doesn't contain the transient field value
BasicStudent deserialized = gson.fromJson(json, BasicStudent.class);
assertThat(deserialized.getMajor()).isNull();
}
@Test
public void givenStudentV2_whenSerializingWithGson_thenIllegalArgumentExceptionIsThrown() {
// Given a class with a class hierarchy that defines multiple fields with the same name
StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");
// When serializing using Gson, then an IllegalArgumentException exception is thrown
Gson gson = new Gson();
assertThatThrownBy(() -> gson.toJson(student)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("declares multiple JSON fields named 'firstName'");
}
@Test
public void givenStudentV2_whenSerializingWithGsonExposeAnnotation_thenSerializes() {
// Given a class with a class hierarchy that defines multiple fields with the same name
StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");
// When serializing using Gson exclude fields without @Expose
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();
// Then ensure the student can be serialized, then deserialized back into an equal instance
String json = gson.toJson(student);
assertThat(gson.fromJson(json, StudentV2.class)).isEqualTo(student);
}
@Test
public void givenStudentV2_whenSerializingWithGsonExclusionStrategy_thenSerializes() {
// Given a class with a class hierarchy that defines multiple fields with the same name
StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");
// When serializing using Gson add an ExclusionStrategy
Gson gson = new GsonBuilder().setExclusionStrategies(new StudentExclusionStrategy())
.create();
// Then ensure the student can be serialized, then deserialized back into an equal instance
assertThat(gson.fromJson(gson.toJson(student), StudentV2.class)).isEqualTo(student);
}
}

View File

@ -22,7 +22,7 @@
</dependencies>
<properties>
<jsoup.version>1.10.2</jsoup.version>
<jsoup.version>1.16.2</jsoup.version>
</properties>
</project>

View File

@ -2,7 +2,7 @@ package com.baeldung.jsoup;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import org.jsoup.safety.Safelist;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -13,7 +13,7 @@ public class PreservingLineBreaksUnitTest {
String strHTML = "<html><body>Hello\nworld</body></html>";
Document.OutputSettings outputSettings = new Document.OutputSettings();
outputSettings.prettyPrint(false);
String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings);
String strWithNewLines = Jsoup.clean(strHTML, "", Safelist.none(), outputSettings);
assertEquals("Hello\nworld", strWithNewLines);
}
@ -33,7 +33,7 @@ public class PreservingLineBreaksUnitTest {
jsoupDoc.select("p").before("\\n");
String str = jsoupDoc.html().replaceAll("\\\\n", "\n");
String strWithNewLines =
Jsoup.clean(str, "", Whitelist.none(), outputSettings);
Jsoup.clean(str, "", Safelist.none(), outputSettings);
assertEquals("Hello\nWorld\nParagraph", strWithNewLines);
}
}

View File

@ -197,7 +197,7 @@
<javapoet.version>1.10.0</javapoet.version>
<mockftpserver.version>2.7.1</mockftpserver.version>
<functionaljava.version>4.8.1</functionaljava.version>
<resilience4j.version>0.12.1</resilience4j.version>
<resilience4j.version>2.1.0</resilience4j.version>
<protonpack.version>1.15</protonpack.version>
<commons-net.version>3.6</commons-net.version>
<renjin.version>3.5-beta72</renjin.version>

View File

@ -43,7 +43,7 @@ public class Resilience4jUnitTest {
// Percentage of failures to start short-circuit
.failureRateThreshold(20)
// Min number of call attempts
.ringBufferSizeInClosedState(5)
.slidingWindowSize(5)
.build();
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
@ -70,7 +70,7 @@ public class Resilience4jUnitTest {
Future<?> taskInProgress = callAndBlock(decorated);
try {
assertThat(bulkhead.isCallPermitted()).isFalse();
assertThat(bulkhead.tryAcquirePermission()).isFalse();
} finally {
taskInProgress.cancel(true);
}

View File

@ -109,7 +109,7 @@
</build>
<properties>
<okhttp.version>4.9.1</okhttp.version>
<okhttp.version>4.12.0</okhttp.version>
<gson.version>2.10.1</gson.version>
<mockwebserver.version>4.9.1</mockwebserver.version>
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>

View File

@ -105,7 +105,7 @@
<properties>
<gson.version>2.10.1</gson.version>
<httpclient.version>4.5.3</httpclient.version>
<com.squareup.okhttp3.version>4.9.1</com.squareup.okhttp3.version>
<com.squareup.okhttp3.version>4.12.0</com.squareup.okhttp3.version>
<googleclient.version>1.23.0</googleclient.version>
<async.http.client.version>2.2.0</async.http.client.version>
<retrofit.version>2.3.0</retrofit.version>

View File

@ -91,7 +91,7 @@
</build>
<properties>
<okhttp.version>3.9.0</okhttp.version>
<okhttp.version>4.12.0</okhttp.version>
<javax.json.version>1.1</javax.json.version>
<osgi.version>6.0.0</osgi.version>
<maven-bundle-plugin.version>3.3.0</maven-bundle-plugin.version>

View File

@ -111,12 +111,12 @@
<poi-scratchpad.version>3.15</poi-scratchpad.version>
<batik-transcoder.version>1.8</batik-transcoder.version>
<poi-ooxml.version>3.15</poi-ooxml.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<flying-saucer-pdf.version>9.1.20</flying-saucer-pdf.version>
<thymeleaf.version>3.1.2.RELEASE</thymeleaf.version>
<flying-saucer-pdf.version>9.3.1</flying-saucer-pdf.version>
<open-html-pdfbox.version>1.0.6</open-html-pdfbox.version>
<open-html-pdf-core.version>1.0.6</open-html-pdf-core.version>
<flying-saucer-pdf-openpdf.version>9.1.22</flying-saucer-pdf-openpdf.version>
<jsoup.version>1.14.2</jsoup.version>
<open-html-pdf-core.version>1.0.10</open-html-pdf-core.version>
<flying-saucer-pdf-openpdf.version>9.2.1</flying-saucer-pdf-openpdf.version>
<jsoup.version>1.16.2</jsoup.version>
</properties>
</project>

View File

@ -164,7 +164,7 @@
<shade.plugin.version>3.2.4</shade.plugin.version>
<install.version>3.0.0-M1</install.version>
<jar.plugin.version>3.2.0</jar.plugin.version>
<javadoc.plugin.version>3.2.0</javadoc.plugin.version>
<javadoc.plugin.version>3.6.2</javadoc.plugin.version>
<resources.plugin.version>3.1.0</resources.plugin.version>
<site.plugin.version>3.9.1</site.plugin.version>
<source.plugin.version>3.2.1</source.plugin.version>

View File

@ -8,7 +8,7 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

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