Merge branch 'eugenp:master' into master

This commit is contained in:
Wynn Teo 2024-03-06 10:07:07 +08:00 committed by GitHub
commit 35f65dc8a2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
447 changed files with 4209 additions and 1873 deletions

View File

@ -7,4 +7,5 @@
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
- [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)

View File

@ -0,0 +1,68 @@
package com.baeldung.algorithms.jugglersequence;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class JugglerSequenceGenerator {
public static List<Integer> byLoop(int n) {
if (n <= 0) {
throw new IllegalArgumentException("The initial integer must be greater than zero.");
}
List<Integer> seq = new ArrayList<>();
int current = n;
seq.add(current);
while (current != 1) {
int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current));
seq.add(next);
current = next;
}
return seq;
}
public static List<Integer> byRecursion(int n) {
if (n <= 0) {
throw new IllegalArgumentException("The initial integer must be greater than zero.");
}
List<Integer> seq = new ArrayList<>();
fillSeqRecursively(n, seq);
return seq;
}
private static void fillSeqRecursively(int current, List<Integer> result) {
result.add(current);
if (current == 1) {
return;
}
int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current));
fillSeqRecursively(next, result);
}
}
public class JugglerSequenceUnitTest {
@Test
void whenGeneratingJugglerSeqUsingLoop_thenGetTheExpectedResult() {
assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byLoop(0));
assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(3));
assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byLoop(4));
assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(9));
assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(21));
assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byLoop(42));
}
@Test
void whenGeneratingJugglerSeqUsingRecursion_thenGetTheExpectedResult() {
assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byRecursion(0));
assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(3));
assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byRecursion(4));
assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(9));
assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(21));
assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byRecursion(42));
}
}

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>4.12.0</okhttp.version>
<okhttp.version>5.0.0-alpha.12</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

@ -14,4 +14,4 @@ This module contains articles about Apache POI.
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
- More articles: [[<-- prev]](../apache-poi)
- More articles: [[<-- prev]](../apache-poi)[[next -->]](../apache-poi-3)

View File

@ -27,7 +27,7 @@
</dependencies>
<properties>
<poi.version>5.2.3</poi.version>
<poi.version>5.2.5</poi.version>
</properties>
</project>

View File

@ -1,4 +1,10 @@
## Relevant Articles
## Apache POI
This module contains articles about Apache POI.
### Relevant Articles:
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
- [Apply Bold Text Style for an Entire Row Using Apache POI](https://www.baeldung.com/appache-poi-apply-bold-text-style-entire-row)
- More articles: [[<-- prev]](../apache-poi-2)

View File

@ -24,50 +24,41 @@
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.ozlerhakan/poiji -->
<dependency>
<groupId>com.github.ozlerhakan</groupId>
<artifactId>poiji</artifactId>
<version>${poiji.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi/5.2.3 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas/4.1.2 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
<version>${poi-ooxml-schemas.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/5.1.1 -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.1.1</version>
<version>${xmlbeans.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
<version>${commons-collections4.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel/0.15.7 -->
<dependency>
<groupId>org.dhatim</groupId>
<artifactId>fastexcel</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader/0.15.7 -->
<dependency>
<groupId>org.dhatim</groupId>
<artifactId>fastexcel-reader</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
@ -77,8 +68,11 @@
<properties>
<poi.version>5.2.5</poi.version>
<poiji.version>4.1.1</poiji.version>
<fastexcel.version>0.15.7</fastexcel.version>
<poi-ooxml-schemas.version>4.1.2</poi-ooxml-schemas.version>
<poiji.version>4.2.0</poiji.version>
<xmlbeans.version>5.2.0</xmlbeans.version>
<commons-collections4.version>4.4</commons-collections4.version>
<fastexcel.version>0.17.0</fastexcel.version>
<jxl.version>2.6.12</jxl.version>
</properties>

View File

@ -60,10 +60,10 @@
</build>
<properties>
<poi.version>5.2.0</poi.version>
<jexcel.version>1.0.6</jexcel.version>
<fastexcel.version>0.15.3</fastexcel.version>
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
<poi.version>5.2.5</poi.version>
<jexcel.version>1.0.9</jexcel.version>
<fastexcel.version>0.17.0</fastexcel.version>
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
</properties>
</project>

View File

@ -37,7 +37,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-plugins-version}</version>
<version>${maven-dependency-plugin.version}</version>
<executions>
<execution>
<id>copy</id>
@ -58,10 +58,7 @@
<properties>
<gson.version>2.10.1</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version>
<commons-codec-version>1.16.0</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
<maven-plugins-version>3.1.1</maven-plugins-version>
<maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
</properties>
</project>

View File

@ -27,7 +27,7 @@
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${awssdk.version}</version>
<version>${aws-java-sdk-v2.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -93,7 +93,6 @@
<properties>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.17.283</awssdk.version>
<reactor.version>3.6.0</reactor.version>
</properties>

View File

@ -18,7 +18,7 @@
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>${aws.java.sdk.version}</version>
<version>${aws-java-sdk-v2.version}</version>
</dependency>
<dependency>
@ -30,19 +30,18 @@
<dependency>
<groupId>org.lucee</groupId>
<artifactId>jets3t</artifactId>
<version>${jets3t-version}</version>
<version>${jets3t.version}</version>
</dependency>
<dependency>
<groupId>org.lucee</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec-version}</version>
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
<properties>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
<commons-codec.version>1.10.L001</commons-codec.version>
<jets3t.version>0.9.4.0014L</jets3t.version>
</properties>
</project>

View File

@ -33,7 +33,7 @@
<properties>
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
<aws-java-sdk-v2.version>2.20.147</aws-java-sdk-v2.version>
<aws-java-sdk-v2.version>2.24.9</aws-java-sdk-v2.version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
</properties>

View File

@ -55,9 +55,7 @@
<arg>-Awarns</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>

View File

@ -157,7 +157,7 @@
<properties>
<groovy-wslite.version>1.1.3</groovy-wslite.version>
<assembly.plugin.version>3.4.2</assembly.plugin.version>
<compiler.plugin.version>3.8.1</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<groovy.compiler.version>3.9.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
</properties>

View File

@ -1,2 +1,3 @@
## Relevant Articles
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
- [Simple Web Server in Java 18](https://www.baeldung.com/simple-web-server-java-18)

View File

@ -22,7 +22,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
<version>${guava.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -29,4 +29,4 @@
<properties>
<vavr.version>0.10.4</vavr.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,54 @@
package com.baeldung.modifyandprint;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public class ModifyAndPrintListElementsUnitTest {
private final Logger log = LoggerFactory.getLogger(ModifyAndPrintListElementsUnitTest.class);
@Test
void whenPrintingInForEach_thenListIsPrinted() {
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
theList.forEach(element -> log.info(element));
}
@Test
void whenUsingModifyAndPrintingSeparately_thenListIsModifiedAndPrinted() {
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
theList.replaceAll(element -> element.toUpperCase());
theList.forEach(element -> log.info(element));
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), theList);
}
@Test
void whenPrintingInMap_thenStreamIsModifiedAndPrinted() {
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
List<String> newList = theList.stream()
.map(element -> {
String newElement = element.toUpperCase();
log.info(newElement);
return newElement;
})
.collect(Collectors.toList());
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
}
@Test
void whenPrintingInPeek_thenStreamIsModifiedAndPrinted() {
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
List<String> newList = theList.stream()
.map(element -> element.toUpperCase())
.peek(element-> log.info(element))
.collect(Collectors.toList());
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
}
}

View File

@ -8,4 +8,5 @@
- [How to Sort LinkedHashMap by Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
- [Collect Stream of entrySet() to a LinkedHashMap](https://www.baeldung.com/java-linkedhashmap-entryset-stream)
- [How to Pretty-Print a Map in Java](https://www.baeldung.com/java-map-pretty-print)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)

View File

@ -35,7 +35,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.1-jre</version>
<version>${guava.version}</version>
</dependency>
</dependencies>

View File

@ -9,3 +9,5 @@
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
- [How to Effectively Unit Test CompletableFuture](https://www.baeldung.com/java-completablefuture-unit-test)
- [How to Collect All Results and Handle Exceptions With CompletableFuture in a Loop](https://www.baeldung.com/java-completablefuture-collect-results-handle-exceptions)
- [CompletableFuture runAsync() vs. supplyAsync() in Java](https://www.baeldung.com/java-completablefuture-runasync-supplyasync)
- [Difference Between thenApply() and thenApplyAsync() in CompletableFuture](https://www.baeldung.com/java-completablefuture-thenapply-thenapplyasync)

View File

@ -37,7 +37,7 @@
</build>
<properties>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<source.version>11</source.version>
<target.version>11</target.version>
</properties>

View File

@ -37,7 +37,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<source.version>11</source.version>
<target.version>11</target.version>
</properties>

View File

@ -17,4 +17,5 @@
- [Validate if a String Is a Valid Geo Coordinate](https://www.baeldung.com/java-geo-coordinates-validation)
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
- [Calculating the Power of Any Number in Java Without Using Math pow() Method](https://www.baeldung.com/java-calculating-the-power-without-math-pow)
- [Solving Rod Cutting Problem in Java](https://www.baeldung.com/java-rod-cutting-problem)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)

View File

@ -14,4 +14,4 @@ This module contains articles about networking in Java
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC Addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)
- [[<-- Prev]](/core-java-modules/core-java-networking) [[Next --> ]](/core-java-modules/core-java-networking-3)

View File

@ -14,4 +14,4 @@ This module contains articles about networking in Java
- [Get Domain Name From Given URL in Java](https://www.baeldung.com/java-domain-name-from-url)
- [Java HttpClient Timeout](https://www.baeldung.com/java-httpclient-timeout)
- [Port Scanning With Java](https://www.baeldung.com/java-port-scanning)
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
- [[<-- Prev]](/core-java-modules/core-java-networking-2) [[Next --> ]](/core-java-modules/core-java-networking-4)

View File

@ -8,3 +8,4 @@
- [Normalize a URL in Java](https://www.baeldung.com/java-url-normalization)
- [Translating Space Characters in URLEncoder](https://www.baeldung.com/java-urlencoder-translate-space-characters)
- [Creating a Custom URL Connection](https://www.baeldung.com/java-custom-url-connection)
- [[<-- Prev]](/core-java-modules/core-java-networking-3)

View File

@ -17,46 +17,43 @@
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>${apache.commons-validator.version}</version>
<version>${commons-validator.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
<version>${httpclient.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
<version>${javax.ws.rs-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.22.2</version>
<version>${jersey-common.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.6</version>
<version>${spring-web.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-networking-4</finalName>
</build>
<properties>
<apache.commons-validator.version>1.7</apache.commons-validator.version>
<jsoup.version>1.16.2</jsoup.version>
<commons-validator.version>1.7</commons-validator.version>
<jsoup.version>1.17.2</jsoup.version>
<httpclient.version>4.5.2</httpclient.version>
<javax.ws.rs-api.version>2.1.1</javax.ws.rs-api.version>
<jersey-common.version>2.22.2</jersey-common.version>
<spring-web.version>6.0.6</spring-web.version>
</properties>
</project>

View File

@ -1,19 +1,21 @@
package com.baeldung.outofmemoryerror;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class OutOfMemoryGCLimitExceed {
public static void addRandomDataToMap() {
Map<Integer, String> dataMap = new HashMap<>();
Random r = new Random();
public static final Random RANDOM = new Random();
public static void addRandomDataToList() {
List<String> dataList = new LinkedList<>();
while (true) {
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
dataList.add(String.valueOf(RANDOM.nextInt()));
}
}
public static void main(String[] args) {
OutOfMemoryGCLimitExceed.addRandomDataToMap();
OutOfMemoryGCLimitExceed.addRandomDataToList();
}
}

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [Java 8 Stream Operation on the Empty List](https://www.baeldung.com/java-empty-list-stream-ops)
- [Get a Range of Items from a Stream in Java](https://www.baeldung.com/java-stream-get-range)

View File

@ -6,3 +6,4 @@ This module contains articles about string-related algorithms.
- [Rotating a Java String By n Characters](https://www.baeldung.com/java-rotate-string-by-n-characters)
- [Remove Characters From a String That Are in the Other String](https://www.baeldung.com/java-strings-character-difference)
- [Run-Length Encoding and Decoding in Java](https://www.baeldung.com/java-rle-compression)
- [Check if a String Is Equal to Its Mirror Reflection](https://www.baeldung.com/java-string-mirror-image-test)

View File

@ -1,2 +1,6 @@
### Relevant Articles:
- [Count Uppercase and Lowercase Letters in a String](https://www.baeldung.com/java-string-count-letters-uppercase-lowercase)
- [Find The Largest Number in a String](https://www.baeldung.com/java-find-largest-number-string)
- [Check if String is Base64 Encoded](https://www.baeldung.com/java-check-string-base64-encoding)
- [Find an Unique Email Address in a List](https://www.baeldung.com/java-find-unique-email-address)
- [Get First n Characters in a String in Java](https://www.baeldung.com/get-first-n-characters-in-a-string-in-java)

View File

@ -13,6 +13,19 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -29,6 +42,8 @@
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.14.0</apache.commons.lang3.version>
<guava.version>33.0.0-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,58 @@
package com.baeldung.firstnchars;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import com.google.common.base.Ascii;
class FirstNCharactersUnitTest {
@Test
void givenString_whenUsingSubstringMethod_thenGetFirstChars() {
String givenInput = "Hello Baeldung Readers";
assertEquals("He", givenInput.substring(0, 2));
}
@Test
void givenString_whenUsingSubSequenceMethod_thenGetFirstChars() {
String givenInput = "Welcome";
assertEquals("Wel", givenInput.subSequence(0, 3));
}
@Test
void givenString_whenUsingStreamApi_thenGetFirstChars() {
String givenInput = "The world is beautiful";
String result = givenInput.chars()
.limit(3)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assertEquals("The", result);
}
@Test
void givenString_whenUsingStringUtilsSubstringMethod_thenGetFirstChars() {
String givenInput = "Baeldung";
assertEquals("Baeld", StringUtils.substring(givenInput, 0, 5));
}
@Test
void givenString_whenUsingStringUtilsLeftMethod_thenGetFirstChars() {
String givenInput = "kindness always wins";
assertEquals("kind", StringUtils.left(givenInput, 4));
}
@Test
void givenString_whenUsingGuavaTruncateMethod_thenGetFirstChars() {
String givenInput = "Tamassint";
assertEquals("Tama", Ascii.truncate(givenInput, 4, ""));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.removetrailingspaces;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
public class RemoveTrailingSpaceOrWhitespaceUnitTest {
private final static String INPUT = " a b c d e \t ";
@Test
void whenUsingTrim_thenBothLeadingAndTrailingWhitespaceAreRemoved() {
String result = INPUT.trim();
assertEquals("a b c d e", result);
}
@Test
void whenUsingReplaceAll_thenGetExpectedResult() {
String result1 = INPUT.replaceAll(" +$", "");
assertEquals(" a b c d e \t", result1);
String result2 = INPUT.replaceAll("\\s+$", "");
assertEquals(" a b c d e", result2);
}
@Test
void whenUsingStripTrailing_thenAllTrailingWhitespaceRemoved() {
String result = INPUT.stripTrailing();
assertEquals(" a b c d e", result);
}
@Test
void whenUsingStringUtilsStripEnd_thenTrailingSpaceRemoved() {
String result = StringUtils.stripEnd(INPUT, " ");
assertEquals(" a b c d e \t", result);
}
}

View File

@ -1,83 +0,0 @@
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

@ -2,42 +2,21 @@ package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
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();
}
public void whenGetMostSignificantBits_thenAssertPositive() {
long randomPositiveLong = Math.abs(UUID.randomUUID().getMostSignificantBits());
assertThat(randomPositiveLong).isNotNegative();
}
@Test
void whenGivenLongValue_thenCheckUniqueness() {
long uniqueValue = generateUniqueLong();
assertThat(uniqueValue).isPositive();
public void whenGetLeastSignificantBits_thenAssertPositive() {
long randomPositiveLong = Math.abs(UUID.randomUUID().getLeastSignificantBits());
assertThat(randomPositiveLong).isNotNegative();
}
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

@ -66,7 +66,7 @@
<properties>
<exchange-rate-api.version>1.0.0-SNAPSHOT</exchange-rate-api.version>
<okhttp.version>4.12.0</okhttp.version>
<okhttp.version>5.0.0-alpha.12</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

@ -15,12 +15,14 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<guava.version>33.0.0-jre</guava.version>
</properties>
</project>

View File

@ -5,12 +5,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>docker-compose-2</artifactId>
<description>Demo project for Spring Boot and Docker - Module docker-compose-2</description>
<packaging>pom</packaging>
<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>
</project>

View File

@ -9,9 +9,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

@ -2,12 +2,12 @@
#
# docker build -f src/main/docker/Dockerfile .
FROM adoptopenjdk:11-jre-hotspot as builder
FROM openjdk:17-jdk-alpine as builder
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract
FROM adoptopenjdk:11-jre-hotspot
FROM openjdk:17-jdk-alpine
COPY --from=builder dependencies/ ./
COPY --from=builder spring-boot-loader/ ./
COPY --from=builder internal-dependencies/ ./

View File

@ -6,6 +6,6 @@
# To run with profiles:
# docker run -e "SPRING_PROFILES_ACTIVE=test1,test2,test3" docker-with-spring-profile:latest
FROM openjdk:11
FROM openjdk:17-jdk-alpine
COPY target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

View File

@ -183,7 +183,7 @@
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
<jsonpath.version>2.8.0</jsonpath.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<compiler.plugin.version>3.1</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
</properties>
</project>

View File

@ -74,7 +74,7 @@
</build>
<properties>
<io.grpc.version>1.40.1</io.grpc.version>
<io.grpc.version>1.62.2</io.grpc.version>
<protoc.version>3.17.2</protoc.version>
<os-maven-plugin.version>1.6.2</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>

View File

@ -24,7 +24,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<version>3.12.1</version>
</plugin>
</plugins>
</build>

View File

@ -8,3 +8,4 @@ This module contains articles about Jackson custom conversions.
- [Serialize Only Fields That Meet a Custom Criteria With Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria)
- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer)
- [OffsetDateTime Serialization With Jackson](https://www.baeldung.com/java-jackson-offsetdatetime)
- [Create JavaType From Class with Jackson](https://www.baeldung.com/java-javatype-class-jackson)

View File

@ -27,7 +27,6 @@
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgs>
<arg>--add-opens=java.base/java.lang.foreign=ALL-UNNAMED</arg>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
@ -41,7 +40,7 @@
<project.version>1.0</project.version>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<maven.compiler.version>3.10.1</maven.compiler.version>
<maven.compiler.version>3.12.1</maven.compiler.version>
<junit.jupiter.version>5.9.0</junit.jupiter.version>
</properties>

View File

@ -1052,7 +1052,7 @@
<!-- Plugin versions -->
<maven-clean-plugin.version>3.1.0</maven-clean-plugin.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.12.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version>
<maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>

View File

@ -872,7 +872,7 @@
<!-- Plugin versions -->
<maven-clean-plugin.version>3.1.0</maven-clean-plugin.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.12.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version>
<maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>

View File

@ -873,7 +873,7 @@
<!-- Plugin versions -->
<maven-clean-plugin.version>3.1.0</maven-clean-plugin.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.12.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version>
<maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>

View File

@ -18,6 +18,11 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,34 @@
package com.baeldung.gson.jsontolist.type;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class ParameterizedTypeImpl implements ParameterizedType {
private final Class<?> rawType;
private final Type[] actualTypeArguments;
private ParameterizedTypeImpl(Class<?> rawType, Type[] actualTypeArguments) {
this.rawType = rawType;
this.actualTypeArguments = actualTypeArguments;
}
public static ParameterizedType make(Class<?> rawType, Type ... actualTypeArguments) {
return new ParameterizedTypeImpl(rawType, actualTypeArguments);
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.gson.jsontolist.type;
public class School {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.gson.jsontolist.type;
public class Student {
private String name;
private String grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}

View File

@ -0,0 +1,129 @@
package com.baeldung.gson.jsontolist.type;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.reflect.TypeParameter;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
public class JsonArrayStringToListUnitTest {
Logger LOGGER = LoggerFactory.getLogger(JsonArrayStringToListUnitTest.class);
final String jsonArrayOfStudents =
"["
+ "{\"name\":\"John\", \"grade\":\"1\"}, "
+ "{\"name\":\"Tom\", \"grade\":\"2\"}, "
+ "{\"name\":\"Ram\", \"grade\":\"3\"}, "
+ "{\"name\":\"Sara\", \"grade\":\"1\"}"
+ "]";
final String jsonArrayOfSchools =
"["
+ "{\"name\":\"St. John\", \"city\":\"Chicago City\"}, "
+ "{\"name\":\"St. Tom\", \"city\":\"New York City\"}, "
+ "{\"name\":\"St. Ram\", \"city\":\"Mumbai\"}, "
+ "{\"name\":\"St. Sara\", \"city\":\"Budapest\"}"
+ "]";
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeToken() {
Gson gson = new Gson();
TypeToken<List<Student>> typeTokenForListOfStudents = new TypeToken<List<Student>>(){};
TypeToken<List<School>> typeTokenForListOfSchools = new TypeToken<List<School>>(){};
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, typeTokenForListOfStudents.getType());
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, typeTokenForListOfSchools.getType());
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFails() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, new ListWithDynamicTypeElement<Student>().getType());
assertFalse(studentsLst.get(0) instanceof Student);
assertThrows(ClassCastException.class, () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)));
}
class ListWithDynamicTypeElement<T> {
Type getType() {
TypeToken<List<T>> typeToken = new TypeToken<List<T>>(){};
return typeToken.getType();
}
}
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingGetParameterized() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getGenericTypeForListFromTypeTokenUsingGetParameterized(Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getGenericTypeForListFromTypeTokenUsingGetParameterized(School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingJsonArray() {
List<Student> studentsLst = createListFromJsonArray(jsonArrayOfStudents, Student.class);
List<School> schoolLst = createListFromJsonArray(jsonArrayOfSchools, School.class);
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFromGuava() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getTypeForListUsingTypeTokenFromGuava(Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getTypeForListUsingTypeTokenFromGuava(School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingParameterizedType() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, ParameterizedTypeImpl.make(List.class, Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, ParameterizedTypeImpl.make(List.class, School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
Type getGenericTypeForListFromTypeTokenUsingGetParameterized(Class elementClass) {
return TypeToken.getParameterized(List.class, elementClass).getType();
}
<T> List<T> createListFromJsonArray(String jsonArray, Type elementType) {
Gson gson = new Gson();
List<T> list = new ArrayList<>();
JsonArray array = gson.fromJson(jsonArray, JsonArray.class);
for(JsonElement element : array) {
T item = gson.fromJson(element, elementType);
list.add(item);
}
return list;
}
<T> Type getTypeForListUsingTypeTokenFromGuava(Class<T> type) {
return new com.google.common.reflect.TypeToken<List<T>>() {}
.where(new TypeParameter<T>() {}, type)
.getType();
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.jsonnodetoarraynode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class JsonNodeToArrayNodeConverterUnitTest {
@Test
void givenJsonNode_whenUsingJsonNodeMethods_thenConvertToArrayNode() throws JsonProcessingException {
int count = 0;
String json = "{\"objects\": [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrayNode = new ObjectMapper().readTree(json).get("objects");
assertNotNull(arrayNode, "The 'objects' array should not be null");
assertTrue(arrayNode.isArray(), "The 'objects' should be an array");
if (arrayNode.isArray()) {
for (final JsonNode objNode : arrayNode) {
assertNotNull(objNode, "Array element should not be null");
count++;
}
}
assertEquals(3, count, "The 'objects' array should have 3 elements");
}
@Test
void givenJsonNode_whenUsingCreateArrayNode_thenConvertToArrayNode() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode originalJsonNode = objectMapper.readTree("{\"objects\": [\"One\", \"Two\", \"Three\"]}");
ArrayNode arrayNode = objectMapper.createArrayNode();
originalJsonNode.get("objects").elements().forEachRemaining(arrayNode::add);
assertEquals("[\"One\",\"Two\",\"Three\"]", arrayNode.toString());
}
@Test
void givenJsonNode_whenUsingStreamSupport_thenConvertToArrayNode() throws Exception {
String json = "{\"objects\": [\"One\", \"Two\", \"Three\"]}";
JsonNode obj = new ObjectMapper().readTree(json);
List<JsonNode> objects = StreamSupport
.stream(obj.get("objects").spliterator(), false)
.collect(Collectors.toList());
assertEquals(3, objects.size(), "The 'objects' list should contain 3 elements");
JsonNode firstObject = objects.get(0);
assertEquals("One", firstObject.asText(), "The first element should be One");
}
@Test
void givenJsonNode_whenUsingIterator_thenConvertToArrayNode() throws Exception {
String json = "{\"objects\": [\"One\", \"Two\", \"Three\"]}";
JsonNode datasets = new ObjectMapper().readTree(json);
Iterator<JsonNode> iterator = datasets.withArray("objects").elements();
int count = 0;
while (iterator.hasNext()) {
JsonNode dataset = iterator.next();
System.out.print(dataset.toString() + " ");
count++;
}
assertEquals(3, count, "The 'objects' list should contain 3 elements");
}
}

View File

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

View File

@ -24,7 +24,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.12.1</version>
<configuration>
<!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
<source>1.8</source>

View File

@ -16,7 +16,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.12.1</version>
<configuration>
<!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
<source>1.8</source>

View File

@ -49,15 +49,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED
--add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
--add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED
--add-opens=java.base/java.lang=ALL-UNNAMED
--add-opens=java.base/java.lang.reflect=ALL-UNNAMED
--add-opens=java.base/java.io=ALL-UNNAMED
--add-opens=java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>

View File

@ -0,0 +1,29 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>libraries-data-io-2</artifactId>
<name>libraries-data-io-3</name>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<google-flatbuffers.version>23.5.26</google-flatbuffers.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>${google-flatbuffers.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,18 @@
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.terrains;
@SuppressWarnings("unused")
public final class Color {
private Color() { }
public static final byte Brown = 0;
public static final byte Red = 1;
public static final byte Green = 2;
public static final byte Blue = 3;
public static final byte White = 4;
public static final String[] names = { "Brown", "Red", "Green", "Blue", "White", };
public static String name(int e) { return names[e]; }
}

View File

@ -0,0 +1,51 @@
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.terrains;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.Table;
@SuppressWarnings("unused")
public final class Effect extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Effect getRootAsEffect(ByteBuffer _bb) { return getRootAsEffect(_bb, new Effect()); }
public static Effect getRootAsEffect(ByteBuffer _bb, Effect obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Effect __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public short damage() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 0; }
public boolean mutateDamage(short damage) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, damage); return true; } else { return false; } }
public static int createEffect(FlatBufferBuilder builder,
int nameOffset,
short damage) {
builder.startTable(2);
Effect.addName(builder, nameOffset);
Effect.addDamage(builder, damage);
return Effect.endEffect(builder);
}
public static void startEffect(FlatBufferBuilder builder) { builder.startTable(2); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); }
public static void addDamage(FlatBufferBuilder builder, short damage) { builder.addShort(1, damage, 0); }
public static int endEffect(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Effect get(int j) { return get(new Effect(), j); }
public Effect get(Effect obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

View File

@ -0,0 +1,59 @@
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.terrains;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.Table;
@SuppressWarnings("unused")
public final class Terrain extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Terrain getRootAsTerrain(ByteBuffer _bb) { return getRootAsTerrain(_bb, new Terrain()); }
public static Terrain getRootAsTerrain(ByteBuffer _bb, Terrain obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Terrain __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public MyGame.terrains.Vec3 pos() { return pos(new MyGame.terrains.Vec3()); }
public MyGame.terrains.Vec3 pos(MyGame.terrains.Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; }
public String name() { int o = __offset(6); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(6, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 6, 1); }
public byte color() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 3; }
public boolean mutateColor(byte color) { int o = __offset(8); if (o != 0) { bb.put(o + bb_pos, color); return true; } else { return false; } }
public String navigation() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; }
public ByteBuffer navigationAsByteBuffer() { return __vector_as_bytebuffer(10, 1); }
public ByteBuffer navigationInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); }
public MyGame.terrains.Effect effects(int j) { return effects(new MyGame.terrains.Effect(), j); }
public MyGame.terrains.Effect effects(MyGame.terrains.Effect obj, int j) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int effectsLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; }
public MyGame.terrains.Effect.Vector effectsVector() { return effectsVector(new MyGame.terrains.Effect.Vector()); }
public MyGame.terrains.Effect.Vector effectsVector(MyGame.terrains.Effect.Vector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static void startTerrain(FlatBufferBuilder builder) { builder.startTable(5); }
public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(1, nameOffset, 0); }
public static void addColor(FlatBufferBuilder builder, byte color) { builder.addByte(2, color, 3); }
public static void addNavigation(FlatBufferBuilder builder, int navigationOffset) { builder.addOffset(3, navigationOffset, 0); }
public static void addEffects(FlatBufferBuilder builder, int effectsOffset) { builder.addOffset(4, effectsOffset, 0); }
public static int createEffectsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startEffectsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endTerrain(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static void finishTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); }
public static void finishSizePrefixedTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); }
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Terrain get(int j) { return get(new Terrain(), j); }
public Terrain get(Terrain obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

View File

@ -0,0 +1,38 @@
// automatically generated by the FlatBuffers compiler, do not modify
package MyGame.terrains;
import java.nio.ByteBuffer;
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.Struct;
@SuppressWarnings("unused")
public final class Vec3 extends Struct {
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Vec3 __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public float x() { return bb.getFloat(bb_pos + 0); }
public void mutateX(float x) { bb.putFloat(bb_pos + 0, x); }
public float y() { return bb.getFloat(bb_pos + 4); }
public void mutateY(float y) { bb.putFloat(bb_pos + 4, y); }
public float z() { return bb.getFloat(bb_pos + 8); }
public void mutateZ(float z) { bb.putFloat(bb_pos + 8, z); }
public static int createVec3(FlatBufferBuilder builder, float x, float y, float z) {
builder.prep(4, 12);
builder.putFloat(z);
builder.putFloat(y);
builder.putFloat(x);
return builder.offset();
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Vec3 get(int j) { return get(new Vec3(), j); }
public Vec3 get(Vec3 obj, int j) { return obj.__assign(__element(j), bb); }
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.flatbuffers;
import static MyGame.terrains.Terrain.addColor;
import static MyGame.terrains.Terrain.addEffects;
import static MyGame.terrains.Terrain.addNavigation;
import static MyGame.terrains.Terrain.endTerrain;
import static MyGame.terrains.Terrain.startTerrain;
import java.nio.ByteBuffer;
import com.google.flatbuffers.FlatBufferBuilder;
import MyGame.terrains.Effect;
import MyGame.terrains.Terrain;
public class MyGameMain {
public byte[] serialiseDesertTerrainData() {
int INITIAL_BUFFER = 1024;
FlatBufferBuilder builder = new FlatBufferBuilder(INITIAL_BUFFER);
int sandstormOffset = builder.createString("Sandstorm");
short damage = 3;
int sandStorm = MyGame.terrains.Effect.createEffect(builder, sandstormOffset, damage);
int droughtOffset = builder.createString("Drought");
short damageDrought = 1;
int drought = MyGame.terrains.Effect.createEffect(builder, droughtOffset, damageDrought);
int[] effects = new int[2];
effects[0] = sandStorm;
effects[1] = drought;
byte color = MyGame.terrains.Color.Brown;
int terrainName = builder.createString("Desert");
int navigationName = builder.createString("south");
int effectOffset = MyGame.terrains.Terrain.createEffectsVector(builder, effects);
startTerrain(builder);
MyGame.terrains.Terrain.addName(builder, terrainName);
addColor(builder, color);
addNavigation(builder, navigationName);
addEffects(builder, effectOffset);
int desert = endTerrain(builder);
builder.finish(desert);
return builder.sizedByteArray();
}
public MyGame.terrains.Terrain deserialiseDataToTerrain(byte[] buffer) {
ByteBuffer buf = ByteBuffer.wrap(buffer);
return Terrain.getRootAsTerrain(buf);
}
public Effect.Vector deserialiseDataToEffect(byte[] buffer) {
ByteBuffer buf = ByteBuffer.wrap(buffer);
return Terrain.getRootAsTerrain(buf)
.effectsVector();
}
}

View File

@ -0,0 +1,25 @@
namespace MyGame.terrains;
enum Color:byte { Brown = 0, Red = 1, Green = 2, Blue = 3, White = 4 }
struct Vec3 {
x:float;
y:float;
z:float;
}
table Terrain {
pos:Vec3; // Struct.
name: string;
color:Color = Blue;
navigation: string;
effects: [Effect];
}
table Effect {
name: string;
damage: short;
}
root_type Terrain;

View File

@ -0,0 +1,43 @@
package flatbuffers;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.flatbuffers.MyGameMain;
import MyGame.terrains.Effect;
public class FlatBufferGameUnitTest {
@Test
public void givenTerrainEffect_whenSerialisedWithValues_returnBytes() {
MyGameMain myGame = new MyGameMain();
byte[] bytes = myGame.serialiseDesertTerrainData();
Assert.assertNotNull(bytes);
}
@Test
public void givenSerialisedBytes_whenDeSerialised_returnsTerrain() {
MyGameMain myGame = new MyGameMain();
byte[] bytes = myGame.serialiseDesertTerrainData();
MyGame.terrains.Terrain terrain = myGame.deserialiseDataToTerrain(bytes);
Assert.assertNotNull(terrain);
Assert.assertEquals(terrain.name(), "Desert");
Assert.assertEquals(terrain.navigation(), "south");
Assert.assertEquals(MyGame.terrains.Color.name(terrain.color()), "Brown");
}
@Test
public void givenSerialisedBytes_whenDeSerialised_returnsTerrainEffect() {
MyGameMain myGame = new MyGameMain();
byte[] bytes = myGame.serialiseDesertTerrainData();
Effect.Vector effectsVector = myGame.deserialiseDataToEffect(bytes);
Assert.assertNotNull(effectsVector);
Assert.assertEquals(effectsVector.get(0).name(), "Sandstorm");
Assert.assertEquals(effectsVector.get(1).name(), "Drought");
Assert.assertEquals(effectsVector.get(1).damage(), 1);
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about IO data processing libraries.
- [Introduction To Docx4J](https://www.baeldung.com/docx4j)
- [Breaking YAML Strings Over Multiple Lines](https://www.baeldung.com/yaml-multi-line)
- [Different Serialization Approaches for Java](https://www.baeldung.com/java-serialization-approaches)
- [A Guide to etcd](https://www.baeldung.com/java-etcd-guide)

View File

@ -175,16 +175,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED
--add-opens java.base/jdk.internal.misc=ALL-UNNAMED
--add-opens java.base/sun.nio.ch=ALL-UNNAMED
--add-opens java.management/com.sun.jmx.mbeanserver=ALL-UNNAMED
--add-opens jdk.internal.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED
--add-opens java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED
--add-opens java.base/java.io=ALL-UNNAMED
--add-opens java.base/java.nio=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.lang=ALL-UNNAMED
</argLine>
</configuration>

View File

@ -109,9 +109,9 @@
</build>
<properties>
<okhttp.version>4.12.0</okhttp.version>
<okhttp.version>5.0.0-alpha.12</okhttp.version>
<gson.version>2.10.1</gson.version>
<mockwebserver.version>4.9.1</mockwebserver.version>
<mockwebserver.version>5.0.0-alpha.12</mockwebserver.version>
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>
<jetty.server.version>9.4.19.v20190610</jetty.server.version>
<rxjava2.version>2.2.11</rxjava2.version>

View File

@ -52,17 +52,10 @@ public class BinaryFileDownloaderUnitTest {
verify(writer).close();
}
@Test(expected = IllegalStateException.class)
public void givenUrlAndResponseWithNullBody_whenDownload_thenExpectIllegalStateException() throws Exception {
@Test(expected = NullPointerException.class)
public void givenUrlAndResponseWithNullBody_whenDownload_thenExpectNullPointerException() throws Exception {
String url = "http://example.com/file";
Call call = mock(Call.class);
when(client.newCall(any(Request.class))).thenReturn(call);
Response response = createResponse(url, null);
when(call.execute()).thenReturn(response);
tested.download(url);
verify(writer, times(0)).write(any(InputStream.class), anyDouble());
}
@NotNull

View File

@ -13,13 +13,11 @@
</parent>
<dependencies>
<!-- Dependencies for response decoder with okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${com.squareup.okhttp3.version}</version>
</dependency>
<!-- Dependencies for google http client -->
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
@ -30,7 +28,6 @@
<artifactId>google-http-client-jackson2</artifactId>
<version>${googleclient.version}</version>
</dependency>
<!-- Retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
@ -46,7 +43,6 @@
<artifactId>adapter-rxjava</artifactId>
<version>${retrofit.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
@ -68,7 +64,6 @@
<artifactId>unirest-java</artifactId>
<version>${unirest.version}</version>
</dependency>
<!-- javalin -->
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
@ -105,7 +100,7 @@
<properties>
<gson.version>2.10.1</gson.version>
<httpclient.version>4.5.3</httpclient.version>
<com.squareup.okhttp3.version>4.12.0</com.squareup.okhttp3.version>
<com.squareup.okhttp3.version>5.0.0-alpha.12</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

@ -13,9 +13,8 @@
</parent>
<dependencies>
<!-- sftp file transfer -->
<dependency>
<groupId>com.jcraft</groupId>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>${jsch.version}</version>
</dependency>
@ -27,7 +26,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>${vfs.version}</version>
<version>${commons-vfs2.version}</version>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
@ -66,12 +65,12 @@
<properties>
<!-- sftp -->
<jsch.version>0.1.55</jsch.version>
<sshj.version>0.37.0</sshj.version>
<vfs.version>2.4</vfs.version>
<zip4j.version>2.9.0</zip4j.version>
<opencsv.version>5.8</opencsv.version>
<spring.version>4.3.8.RELEASE</spring.version>
<jsch.version>0.2.16</jsch.version>
<sshj.version>0.38.0</sshj.version>
<commons-vfs2.version>2.9.0</commons-vfs2.version>
<zip4j.version>2.11.5</zip4j.version>
<opencsv.version>5.9</opencsv.version>
<spring.version>6.1.4</spring.version>
</properties>
</project>

View File

@ -30,6 +30,12 @@
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
</dependencies>
<build>
@ -73,6 +79,7 @@
<properties>
<jetty.version>9.4.27.v20200227</jetty.version>
<alpn.version>8.1.11.v20170118</alpn.version>
<netty.version>4.1.104.Final</netty.version>
</properties>
</project>

View File

@ -0,0 +1,77 @@
package com.baeldung.netty.customhandlersandlisteners;
import java.util.Scanner;
import com.baeldung.netty.customhandlersandlisteners.handler.ClientEventHandler;
import com.baeldung.netty.customhandlersandlisteners.listener.ChannelInfoListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class ChatClientMain {
private static final String SYSTEM_USER = System.getProperty("user.name");
private static String user;
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try (Scanner scanner = new Scanner(System.in)) {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addFirst(new StringDecoder(), new ClientEventHandler(), new StringEncoder());
}
});
ChannelFuture future = bootstrap.connect(ChatServerMain.HOST, ChatServerMain.PORT)
.sync();
future.addListener(new ChannelInfoListener("connected to server"));
Channel channel = future.sync()
.channel();
messageLoop(scanner, channel);
channel.close();
} catch (Throwable e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
group.shutdownGracefully();
}
}
private static void messageLoop(Scanner scanner, Channel channel) throws InterruptedException {
Thread.sleep(50);
if (user == null) {
System.out.printf("your name [%s]: ", SYSTEM_USER);
user = scanner.nextLine();
if (user.isEmpty())
user = SYSTEM_USER;
}
System.out.print("> ");
while (scanner.hasNext()) {
String message = scanner.nextLine();
if (message.equals("exit"))
break;
ChannelFuture sent = channel.writeAndFlush(user + ";" + message);
sent.addListener(new ChannelInfoListener("message sent"));
sent.addListener(future -> System.out.print("> "));
}
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.netty.customhandlersandlisteners;
import com.baeldung.netty.customhandlersandlisteners.handler.ServerEventHandler;
import com.baeldung.netty.customhandlersandlisteners.listener.ChannelInfoListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public final class ChatServerMain {
public static final String HOST = "localhost";
public static final int PORT = 8081;
public static void main(String[] args) {
EventLoopGroup serverGroup = new NioEventLoopGroup(1);
EventLoopGroup clientGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(serverGroup, clientGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addFirst(new StringDecoder(), new ServerEventHandler(), new StringEncoder());
}
});
ChannelFuture future = bootstrap.bind(HOST, PORT)
.sync();
System.out.println("chat server started. ready to accept clients.");
future.addListener(new ChannelInfoListener("server online"));
future.channel()
.closeFuture()
.sync();
} catch (Throwable e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
serverGroup.shutdownGracefully();
clientGroup.shutdownGracefully();
}
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.netty.customhandlersandlisteners.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ClientEventHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext context, String msg) {
System.out.println(msg);
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.netty.customhandlersandlisteners.handler;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import com.baeldung.netty.customhandlersandlisteners.listener.ChannelInfoListener;
import com.baeldung.netty.customhandlersandlisteners.model.Message;
import com.baeldung.netty.customhandlersandlisteners.model.OfflineMessage;
import com.baeldung.netty.customhandlersandlisteners.model.OnlineMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ServerEventHandler extends SimpleChannelInboundHandler<String> {
private static final Map<String, Channel> clients = new HashMap<>();
private static final int MAX_HISTORY = 5;
private static final Queue<String> history = new LinkedList<>();
private void handleBroadcast(Message message, ChannelHandlerContext context) {
final String channelId = id(context.channel());
System.out.printf("[clients: %d] message: %s\n", clients.size(), message);
clients.forEach((id, channel) -> {
if (!id.equals(channelId)) {
ChannelFuture relay = channel.writeAndFlush(message.toString());
relay.addListener(new ChannelInfoListener("message relayed to " + id));
}
});
history.add(message.toString() + "\n");
if (history.size() > MAX_HISTORY)
history.poll();
}
@Override
public void channelRead0(ChannelHandlerContext context, String msg) {
handleBroadcast(Message.parse(msg), context);
}
@Override
public void channelActive(final ChannelHandlerContext context) {
Channel channel = context.channel();
clients.put(id(channel), channel);
history.forEach(channel::writeAndFlush);
handleBroadcast(new OnlineMessage(id(channel)), context);
}
@Override
public void channelInactive(ChannelHandlerContext context) {
Channel channel = context.channel();
clients.remove(id(channel));
handleBroadcast(new OfflineMessage(id(channel)), context);
}
private static String id(Channel channel) {
return channel.id()
.asShortText();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.netty.customhandlersandlisteners.listener;
import java.time.Instant;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
public class ChannelInfoListener implements GenericFutureListener<ChannelFuture> {
private final String event;
public ChannelInfoListener(String event) {
this.event = event;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel channel = future.channel();
String status = "OK";
if (!future.isSuccess()) {
status = "FAILED";
future.cause()
.printStackTrace();
}
System.out.printf("%s - channel#%s %s: %s%n", Instant.now(), channel.id()
.asShortText(), status, event);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.netty.customhandlersandlisteners.model;
import java.time.Instant;
public class Message {
private final Instant time;
private final String user;
private final String message;
public Message(String user, String message) {
this.time = Instant.now();
this.user = user;
this.message = message;
}
public Instant getTime() {
return time;
}
public String getUser() {
return user;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return time + " - " + user + ": " + message;
}
public static Message parse(String string) {
String[] arr = string.split(";", 2);
return new Message(arr[0], arr[1]);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.netty.customhandlersandlisteners.model;
public class OfflineMessage extends Message {
public OfflineMessage(String info) {
super("system", "client went offline: " + info);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.netty.customhandlersandlisteners.model;
public class OnlineMessage extends Message {
public OnlineMessage(String info) {
super("system", "client online: " + info);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.netty.customhandlersandlisteners;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.netty.customhandlersandlisteners.handler.ClientEventHandler;
import com.baeldung.netty.customhandlersandlisteners.handler.ServerEventHandler;
import io.netty.channel.embedded.EmbeddedChannel;
class ChatIntegrationTest {
private static final String MSG_1 = "Alice;Anyone there?!";
private static final String MSG_2 = "Bob;Hi, Alice!";
@Test
void whenMessagesWrittenToServer_thenMessagesConsumed() {
EmbeddedChannel server = new EmbeddedChannel(new ServerEventHandler());
assertTrue(server.writeOutbound(MSG_1));
assertTrue(server.writeOutbound(MSG_2));
assertEquals(2, server.outboundMessages()
.size());
assertEquals(MSG_1, server.readOutbound()
.toString());
assertEquals(MSG_2, server.readOutbound()
.toString());
server.close();
}
@Test
void whenClientReceivesMessages_thenMessagesConsumed() {
EmbeddedChannel client = new EmbeddedChannel(new ClientEventHandler());
assertTrue(client.writeOutbound(MSG_1));
assertTrue(client.writeOutbound(MSG_2));
assertEquals(2, client.outboundMessages()
.size());
assertEquals(MSG_1, client.readOutbound()
.toString());
assertEquals(MSG_2, client.readOutbound()
.toString());
client.close();
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.netty.customhandlersandlisteners;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import com.baeldung.netty.customhandlersandlisteners.model.Message;
class MessageUnitTest {
@Test
void whenBroadcastMessage_thenParsedSuccessfully() {
String input = "Bob;Hello, world; go!";
Message message = Message.parse(input);
assertEquals("Bob", message.getUser());
assertEquals("Hello, world; go!", message.getMessage());
assertNotNull(message.getTime());
}
@Test
void whenNewMessage_thenExpectedFormat() {
Message message = new Message("Alice", "Testing");
Instant time = message.getTime();
String expected = time + " - Alice: Testing";
assertEquals(expected, message.toString());
}
}

View File

@ -49,11 +49,11 @@
<properties>
<jool.version>0.9.12</jool.version>
<parallel-collectors.version>1.1.0</parallel-collectors.version>
<parallel-collectors.version>2.6.0</parallel-collectors.version>
<vavr.version>0.9.0</vavr.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<streamex.version>0.8.1</streamex.version>
<protonpack.version>1.15</protonpack.version>
</properties>
</project>
</project>

View File

@ -1,5 +1,6 @@
package com.baeldung.parallel_collectors;
import com.pivovarit.collectors.ParallelCollectors;
import org.junit.Test;
import java.util.Arrays;
@ -12,13 +13,15 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.pivovarit.collectors.ParallelCollectors.parallel;
import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered;
import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection;
import static com.pivovarit.collectors.ParallelCollectors.parallelToList;
import static com.pivovarit.collectors.ParallelCollectors.parallelToMap;
import static com.pivovarit.collectors.ParallelCollectors.parallelToOrderedStream;
import static com.pivovarit.collectors.ParallelCollectors.parallelToStream;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class ParallelCollectorsUnitTest {
@ -28,21 +31,21 @@ public class ParallelCollectorsUnitTest {
List<String> results = ids.parallelStream()
.map(i -> fetchById(i))
.collect(Collectors.toList());
.collect(toList());
System.out.println(results);
assertThat(results).containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldProcessInParallelWithParallelCollectors() {
public void shouldCollectInParallel() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<List<String>> results = ids.stream()
.collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4));
CompletableFuture<Stream<String>> results = ids.stream()
.collect(parallel(ParallelCollectorsUnitTest::fetchById, executor, 4));
System.out.println(results.join());
assertThat(results.join()).containsExactly("user-1", "user-2", "user-3");
}
@Test
@ -51,11 +54,10 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.stream()
.collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4))
.join();
CompletableFuture<List<String>> results = ids.stream()
.collect(parallel(ParallelCollectorsUnitTest::fetchById, toList(), executor, 4));
System.out.println(results); // [user-1, user-2, user-3]
assertThat(results.join()).containsExactly("user-1", "user-2", "user-3");
}
@Test
@ -64,11 +66,11 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.stream()
.collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4))
.join();
CompletableFuture<List<String>> results = ids.stream()
.collect(parallel(i -> fetchById(i), toCollection(LinkedList::new), executor, 4));
System.out.println(results); // [user-1, user-2, user-3]
assertThat(results.join())
.containsExactly("user-1", "user-2", "user-3");
}
@Test
@ -77,12 +79,13 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, List<String>> results = ids.stream()
.collect(parallelToStream(i -> fetchById(i), executor, 4))
.thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length())))
.join();
CompletableFuture<Map<Integer, List<String>>> results = ids.stream()
.collect(parallel(i -> fetchById(i), executor, 4))
.thenApply(stream -> stream.collect(Collectors.groupingBy(String::length)));
System.out.println(results); // [user-1, user-2, user-3]
assertThat(results.join())
.hasSize(1)
.containsEntry(6, Arrays.asList("user-1", "user-2", "user-3"));
}
@Test
@ -91,9 +94,10 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
ids.stream()
.collect(parallel(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4))
.forEach(System.out::println);
Stream<String> result = ids.stream()
.collect(parallelToStream(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4));
assertThat(result).contains("user-1", "user-2", "user-3");
}
@Test
@ -102,9 +106,10 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
ids.stream()
.collect(parallelOrdered(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4))
.forEach(System.out::println);
Stream<String> result = ids.stream()
.collect(parallelToOrderedStream(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4));
assertThat(result).containsExactly("user-1", "user-2", "user-3");
}
@Test
@ -113,24 +118,14 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, executor, 4))
.join();
CompletableFuture<Map<Integer, String>> results = ids.stream()
.collect(parallel(i -> i, Collectors.toMap(i -> i, ParallelCollectorsUnitTest::fetchById), executor, 4));
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
}
@Test
public void shouldCollectToTreeMap() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, executor, 4))
.join();
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
assertThat(results.join())
.hasSize(3)
.containsEntry(1, "user-1")
.containsEntry(2, "user-2")
.containsEntry(3, "user-3");
}
@Test
@ -139,11 +134,24 @@ public class ParallelCollectorsUnitTest {
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<Integer, String> results = ids.stream()
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, (s1, s2) -> s1, executor, 4))
.join();
CompletableFuture<Map<Integer, String>> results = ids.stream()
.collect(parallel(i -> i, Collectors.toMap(i -> i, ParallelCollectorsUnitTest::fetchById, (u1, u2) -> u1, TreeMap::new), executor, 4));
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
assertThat(results.join())
.hasSize(3)
.containsEntry(1, "user-1")
.containsEntry(2, "user-2")
.containsEntry(3, "user-3");
}
@Test
public void shouldCollectListOfFutures() {
List<CompletableFuture<Integer>> futures = Arrays.asList(completedFuture(1), completedFuture(2), completedFuture(3));
CompletableFuture<List<Integer>> result = futures.stream()
.collect(ParallelCollectors.toFuture());
assertThat(result.join()).containsExactly(1, 2, 3);
}
private static String fetchById(int id) {

View File

@ -205,15 +205,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED
--add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
--add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED
--add-opens=java.base/java.lang=ALL-UNNAMED
--add-opens=java.base/java.lang.reflect=ALL-UNNAMED
--add-opens=java.base/java.io=ALL-UNNAMED
--add-opens=java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>

View File

@ -20,6 +20,7 @@
<module>logback</module>
<module>log-mdc</module>
<module>tinylog2</module>
<module>logging-techniques</module>
</modules>
</project>

View File

@ -58,6 +58,13 @@
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>

View File

@ -33,13 +33,15 @@
</dependencies>
<build>
<finalName>lombok</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<properties>

View File

@ -10,9 +10,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>
<modules>

View File

@ -22,7 +22,7 @@
</build>
<properties>
<compiler.plugin.version>3.11.0</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<source.version>9</source.version>
<target.version>9</target.version>
</properties>

View File

@ -40,7 +40,7 @@
</build>
<properties>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<source.version>1.9</source.version>
<target.version>1.9</target.version>
</properties>

View File

@ -19,6 +19,7 @@
</modules>
<!--comment section below to provoke version collision in project-collision module -->
<!--Don't Update the version here as it shows the collision when compiling with maven.-->
<dependencyManagement>
<dependencies>
<dependency>

View File

@ -12,6 +12,7 @@
</parent>
<dependencies>
<!--Don't Update the version here as it shows the collision when compiling with maven.-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>

View File

@ -12,6 +12,7 @@
</parent>
<dependencies>
<!--Don't Update the version here as it shows the collision when compiling with maven.-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>

View File

@ -152,7 +152,7 @@
<jdk.version>17</jdk.version>
<release.version>17</release.version>
<packaging>jar</packaging>
<compiler.plugin.version>3.7.0</compiler.plugin.version>
<compiler.plugin.version>3.12.1</compiler.plugin.version>
<micronaut.runtime>netty</micronaut.runtime>
<shade.plugin.version>3.2.0</shade.plugin.version>
</properties>

View File

@ -29,7 +29,6 @@
<configuration>
<argLine>
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>

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