Merge branch 'master' into master
This commit is contained in:
commit
04e10f4adf
@ -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)
|
||||
|
@ -1,2 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
|
||||
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
|
||||
|
@ -10,4 +10,6 @@
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.apache.camel.impl.engine" level="WARN"/>
|
||||
</configuration>
|
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="ch.qos.logback.classic.joran.action" level="WARN"/>
|
||||
</configuration>
|
@ -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)
|
||||
|
@ -27,7 +27,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -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)
|
@ -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>
|
||||
|
||||
|
@ -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>
|
@ -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>
|
@ -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>
|
||||
|
||||
|
@ -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>
|
@ -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>
|
||||
|
||||
|
@ -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>
|
||||
|
@ -1,61 +1,71 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import groovy.io.FileType
|
||||
import groovy.io.FileVisitResult
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class TraverseFileTreeUnitTest {
|
||||
@Test
|
||||
void whenUsingEachFile_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException)
|
||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||
var files = []
|
||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileMatch_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachDirRecurse { dir ->
|
||||
println "$dir.parent $dir.name"
|
||||
files.add("$dir.parent $dir.name")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||
var files = []
|
||||
new File('src/main').traverse { file ->
|
||||
if (file.directory && file.name == 'groovy') {
|
||||
FileVisitResult.SKIP_SUBTREE
|
||||
} else {
|
||||
println "$file.parent - $file.name"
|
||||
files.add("$file.parent - $file.name")
|
||||
}
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
}
|
||||
|
@ -2,6 +2,8 @@ package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertFalse
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@Test
|
||||
@ -19,6 +21,7 @@ class DollarSlashyString {
|
||||
- $/$$
|
||||
/$
|
||||
|
||||
print(dollarSlashy)
|
||||
//print(dollarSlashy)
|
||||
assertFalse(dollarSlashy.isEmpty())
|
||||
}
|
||||
}
|
||||
|
@ -45,7 +45,6 @@
|
||||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
|
@ -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)
|
||||
|
@ -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>
|
||||
|
@ -60,7 +60,6 @@
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<org.json.version>20230618</org.json.version>
|
||||
</properties>
|
||||
</project>
|
@ -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)
|
||||
|
@ -32,17 +32,22 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.2-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -63,6 +68,9 @@
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
<guava.version>32.1.2-jre</guava.version>
|
||||
<jmh.version>1.37</jmh.version>
|
||||
<commons-collections.version>4.4</commons-collections.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -0,0 +1,202 @@
|
||||
package com.baeldung.map.prettyprintmap;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class PrettyPrintMapUnitTest {
|
||||
|
||||
private static final Map<String, Object> MAP;
|
||||
|
||||
static {
|
||||
// using LinkedHashMap to keep insertion order, helpful in assertions
|
||||
MAP = new LinkedHashMap<>();
|
||||
MAP.put("one", 1);
|
||||
MAP.put("two", 2);
|
||||
|
||||
Map<String, Integer> innerMap = new LinkedHashMap<>();
|
||||
innerMap.put("ten", 10);
|
||||
innerMap.put("eleven", 11);
|
||||
|
||||
MAP.put("inner", innerMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenToString_thenOneLine() {
|
||||
String result = MAP.toString();
|
||||
|
||||
String expected = "{one=1, two=2, inner={ten=10, eleven=11}}";
|
||||
Assertions.assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenSimpleForEachLoop_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : MAP.entrySet()) {
|
||||
result.append(String.format("%-15s : %s%n", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenRecursionForEachLoop_thenPrettyPrint() {
|
||||
String result = printMap(0, MAP);
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner :\n" +
|
||||
" ten : 10\n" +
|
||||
" eleven : 11\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenStream_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
MAP.forEach((k, v) -> result.append(String.format("%-15s : %s%n", k, v)));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenExtendedStream_thenPrettyPrintWithoutNested() {
|
||||
String result = MAP.entrySet().stream()
|
||||
.map(entry -> String.format("%-15s : %s", entry.getKey(), entry.getValue()))
|
||||
.collect(Collectors.joining("\n"));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
@Test
|
||||
void givenMap_whenJackson_thenPrettyPrint() throws JsonProcessingException {
|
||||
String result = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\" : 1,\n" +
|
||||
" \"two\" : 2,\n" +
|
||||
" \"inner\" : {\n" +
|
||||
" \"ten\" : 10,\n" +
|
||||
" \"eleven\" : 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGson_thenPrettyPrint() {
|
||||
String result = new GsonBuilder().setPrettyPrinting().create().toJson(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\": 1,\n" +
|
||||
" \"two\": 2,\n" +
|
||||
" \"inner\": {\n" +
|
||||
" \"ten\": 10,\n" +
|
||||
" \"eleven\": 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsDebugPrint_thenPrettyPrintWithClassNames() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.debugPrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1 java.lang.Integer\n" +
|
||||
" two = 2 java.lang.Integer\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10 java.lang.Integer\n" +
|
||||
" eleven = 11 java.lang.Integer\n" +
|
||||
" } java.util.LinkedHashMap\n" +
|
||||
"} java.util.LinkedHashMap\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsVerbosePrint_thenPrettyPrint() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.verbosePrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1\n" +
|
||||
" two = 2\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10\n" +
|
||||
" eleven = 11\n" +
|
||||
" }\n" +
|
||||
"}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGuavaJoiner_thenPrettyPrintWithoutNested() {
|
||||
String result = Joiner.on(",\n").withKeyValueSeparator("=").join(MAP);
|
||||
|
||||
String expected =
|
||||
"one=1,\n" +
|
||||
"two=2,\n" +
|
||||
"inner={ten=10, eleven=11}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
private static String printMap(int leftPadding, Map<?, ?> map) {
|
||||
StringBuilder ret = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
if (entry.getValue() instanceof Map) {
|
||||
ret.append(String.format("%-15s :%n", entry.getKey()));
|
||||
ret.append(printMap(leftPadding + 4, (Map<?, ?>) entry.getValue()));
|
||||
}
|
||||
else {
|
||||
ret.append(String.format("%" + (leftPadding > 0 ? leftPadding : "") + "s" // adding padding
|
||||
+ "%-15s : %s%n",
|
||||
"", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
return ret.toString();
|
||||
}
|
||||
|
||||
}
|
@ -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>
|
||||
|
||||
|
@ -60,14 +60,15 @@ public class HashtableUnitTest {
|
||||
table.put(new Word("dog"), "another animal");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
// System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
Word key = it.next();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,12 +86,13 @@ public class HashtableUnitTest {
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
// System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
Word key = enumKey.nextElement();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -110,7 +112,8 @@ public class HashtableUnitTest {
|
||||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Word, String> entry = it.next();
|
||||
System.out.println(entry.getValue());
|
||||
// System.out.println(entry.getValue());
|
||||
assertNotNull(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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)
|
||||
|
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
@ -4,7 +4,7 @@ import java.util.function.Function;
|
||||
|
||||
public class Currying {
|
||||
|
||||
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
|
||||
private static Function<Double, Function<Double, Double>> weight = gravity -> mass -> mass * gravity;
|
||||
|
||||
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
||||
|
||||
|
@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.eclipse.jetty.server.handler" level="WARN"/>
|
||||
<logger name="org.mockserver.log" level="WARN"/>
|
||||
</configuration>
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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)
|
@ -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>
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -23,9 +23,9 @@ public class SSLDebugLogger {
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
logger.info("Response from " + url + ":");
|
||||
logger.debug("Response from " + url + ":");
|
||||
while ((line = reader.readLine()) != null) {
|
||||
logger.info(line);
|
||||
logger.debug(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
@ -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)
|
||||
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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>
|
||||
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.finduniqueemails;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class FindUniqueEmailsUnitTest {
|
||||
String[] emailList = {"user@example.com", "user@example.com", "user@gmail.com", "admin@example.com", "USER@example.com"};
|
||||
Set<String> expectedUniqueEmails = new HashSet<>();
|
||||
|
||||
FindUniqueEmailsUnitTest() {
|
||||
expectedUniqueEmails.add("user@example.com");
|
||||
expectedUniqueEmails.add("user@gmail.com");
|
||||
expectedUniqueEmails.add("admin@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmailList_whenUsingStringManipulation_thenFindUniqueEmails() {
|
||||
Set<String> uniqueEmails = new HashSet<>();
|
||||
for (String email : emailList) {
|
||||
uniqueEmails.add(email.toLowerCase());
|
||||
}
|
||||
|
||||
assertEquals(expectedUniqueEmails, uniqueEmails);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmailList_whenUsingJavaStreams_thenFindUniqueEmails() {
|
||||
Set<String> uniqueEmails = Arrays.stream(emailList)
|
||||
.map(String::toLowerCase)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertEquals(expectedUniqueEmails, uniqueEmails);
|
||||
}
|
||||
}
|
@ -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, ""));
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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>
|
@ -1,4 +1,4 @@
|
||||
FROM openjdk:11
|
||||
FROM openjdk:17-alpine
|
||||
MAINTAINER baeldung.com
|
||||
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||
|
@ -8,9 +8,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -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>
|
@ -95,10 +95,10 @@ dependencies {
|
||||
[group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'],
|
||||
[group: 'org.springframework', name: 'spring-aop', version: '4.3.5.RELEASE']
|
||||
)
|
||||
testImplementation('org.hibernate:hibernate-core:5.2.12.Final') {
|
||||
testImplementation('org.hibernate.orm:hibernate-core:6.4.2.Final') {
|
||||
transitive = true
|
||||
}
|
||||
runtimeOnly(group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final') {
|
||||
runtimeOnly(group: 'org.hibernate.orm', name: 'hibernate-core', version: '6.4.2.Final') {
|
||||
transitive = false
|
||||
}
|
||||
runtimeOnly "org.codehaus.groovy:groovy-all:2.4.11@jar"
|
||||
|
@ -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>
|
||||
|
@ -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)
|
||||
|
@ -36,7 +36,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<reflections.version>0.9.11</reflections.version>
|
||||
</properties>
|
||||
|
||||
|
@ -31,8 +31,4 @@
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -41,7 +41,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>
|
||||
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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");
|
||||
if (arrayNode.isArray()) {
|
||||
for (final JsonNode objNode : arrayNode) {
|
||||
assertNotNull(objNode, "Array element should not be null");
|
||||
count++;
|
||||
}
|
||||
}
|
||||
assertNotNull(arrayNode, "The 'objects' array should not be null");
|
||||
assertTrue(arrayNode.isArray(), "The 'objects' should be an array");
|
||||
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");
|
||||
}
|
||||
}
|
@ -22,7 +22,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jsoup.version>1.16.2</jsoup.version>
|
||||
<jsoup.version>1.17.2</jsoup.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -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>
|
||||
|
@ -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>
|
||||
|
29
libraries-data-io-2/pom.xml
Normal file
29
libraries-data-io-2/pom.xml
Normal 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>
|
@ -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]; }
|
||||
}
|
||||
|
@ -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); }
|
||||
}
|
||||
}
|
||||
|
@ -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); }
|
||||
}
|
||||
}
|
||||
|
@ -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); }
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -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;
|
@ -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);
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -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>
|
@ -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>
|
@ -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("> "));
|
||||
}
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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]);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.netty.customhandlersandlisteners.model;
|
||||
|
||||
public class OnlineMessage extends Message {
|
||||
|
||||
public OnlineMessage(String info) {
|
||||
super("system", "client online: " + info);
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
@ -49,7 +49,7 @@
|
||||
|
||||
<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>
|
||||
|
@ -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) {
|
||||
|
@ -20,6 +20,7 @@
|
||||
<module>logback</module>
|
||||
<module>log-mdc</module>
|
||||
<module>tinylog2</module>
|
||||
<module>logging-techniques</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user