Merge branch 'eugenp:master' into PR-7386
This commit is contained in:
commit
03cab9f3c3
|
@ -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>
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
|
@ -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>
|
|
@ -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,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>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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>
|
||||
|
|
|
@ -152,7 +152,7 @@
|
|||
<jdk.version>17</jdk.version>
|
||||
<release.version>17</release.version>
|
||||
<packaging>jar</packaging>
|
||||
<compiler.plugin.version>3.7.0</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<micronaut.runtime>netty</micronaut.runtime>
|
||||
<shade.plugin.version>3.2.0</shade.plugin.version>
|
||||
</properties>
|
||||
|
|
|
@ -229,8 +229,8 @@
|
|||
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
|
||||
<maven-resources-plugin.version>3.3.0</maven-resources-plugin.version>
|
||||
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
||||
<spring-boot.version>3.2.2</spring-boot.version>
|
||||
<junit-jupiter.version>5.10.2</junit-jupiter.version>
|
||||
<spring-boot.version>3.1.5</spring-boot.version>
|
||||
<junit-jupiter.version>5.8.2</junit-jupiter.version>
|
||||
<native-build-tools-plugin.version>0.9.17</native-build-tools-plugin.version>
|
||||
<logback.version>1.4.4</logback.version>
|
||||
<slf4j.version>2.0.3</slf4j.version>
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
|
@ -74,12 +74,6 @@
|
|||
<version>${reactor.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<version>${de.flapdoodle.embed.mongo.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
|
@ -95,6 +89,17 @@
|
|||
<artifactId>reactor-netty-http</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>mongodb</artifactId>
|
||||
<version>${mongodb.testcontainer.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -114,9 +119,9 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<axon-bom.version>4.6.3</axon-bom.version>
|
||||
<de.flapdoodle.embed.mongo.version>3.4.8</de.flapdoodle.embed.mongo.version>
|
||||
<axon-bom.version>4.9.3</axon-bom.version>
|
||||
<reactor.version>3.6.0</reactor.version>
|
||||
<mongodb.testcontainer.version>1.17.6</mongodb.testcontainer.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -18,7 +18,6 @@ import com.mongodb.client.model.IndexOptions;
|
|||
import com.mongodb.client.model.Indexes;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
import groovyjarjarantlr4.v4.runtime.misc.NotNull;
|
||||
|
||||
import org.axonframework.config.ProcessingGroup;
|
||||
import org.axonframework.eventhandling.EventHandler;
|
||||
|
@ -30,6 +29,7 @@ import org.reactivestreams.Publisher;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
@ -172,7 +172,7 @@ public class MongoOrdersEventHandler implements OrdersEventHandler {
|
|||
.toString());
|
||||
}
|
||||
|
||||
private Order documentToOrder(@NotNull Document document) {
|
||||
private Order documentToOrder(@NonNull Document document) {
|
||||
Order order = new Order(document.getString(ORDER_ID_PROPERTY_NAME));
|
||||
Document products = document.get(PRODUCTS_PROPERTY_NAME, Document.class);
|
||||
products.forEach((k, v) -> order.getProducts()
|
||||
|
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.mongodb.client.MongoClient;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.testcontainers.containers.MongoDBContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
|
||||
@DataMongoTest
|
||||
public class MongoOrdersEventHandlerLiveTest extends AbstractOrdersEventHandlerUnitTest {
|
||||
|
||||
@Autowired
|
||||
MongoClient mongoClient;
|
||||
|
||||
@Container
|
||||
static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:6.0").withExposedPorts(27017);
|
||||
|
||||
@DynamicPropertySource
|
||||
static void mongoDbProperties(DynamicPropertyRegistry registry) {
|
||||
|
||||
mongoDBContainer.start();
|
||||
registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected OrdersEventHandler getHandler() {
|
||||
mongoClient.getDatabase("axonframework")
|
||||
.drop();
|
||||
return new MongoOrdersEventHandler(mongoClient, emitter);
|
||||
}
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
package com.baeldung.axon.querymodel;
|
||||
|
||||
import com.mongodb.client.MongoClient;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
|
||||
|
||||
@DataMongoTest
|
||||
public class MongoOrdersEventHandlerUnitTest extends AbstractOrdersEventHandlerUnitTest {
|
||||
|
||||
@Autowired
|
||||
MongoClient mongoClient;
|
||||
|
||||
@Override
|
||||
protected OrdersEventHandler getHandler() {
|
||||
mongoClient.getDatabase("axonframework")
|
||||
.drop();
|
||||
return new MongoOrdersEventHandler(mongoClient, emitter);
|
||||
}
|
||||
}
|
|
@ -68,7 +68,7 @@
|
|||
<properties>
|
||||
<source.version>9</source.version>
|
||||
<target.version>9</target.version>
|
||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<appmodules.version>1.0</appmodules.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -160,7 +160,7 @@
|
|||
<uberjar.name>benchmarks</uberjar.name>
|
||||
<clean.plugin.version>3.1.0</clean.plugin.version>
|
||||
<deploy.plugin.version>3.0.0-M1</deploy.plugin.version>
|
||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<shade.plugin.version>3.2.4</shade.plugin.version>
|
||||
<install.version>3.0.0-M1</install.version>
|
||||
<jar.plugin.version>3.2.0</jar.plugin.version>
|
||||
|
|
|
@ -12,18 +12,6 @@
|
|||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>9</source>
|
||||
<target>9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -38,8 +26,17 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<calcite.version>1.34.0</calcite.version>
|
||||
<calcite.version>1.36.0</calcite.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -92,7 +92,7 @@
|
|||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<javaee-web-api.version>8.0.1</javaee-web-api.version>
|
||||
<maven.war-plugin.version>3.3.1</maven.war-plugin.version>
|
||||
<maven.compiler-plugin.version>3.8.1</maven.compiler-plugin.version>
|
||||
<maven.compiler-plugin.version>3.12.1</maven.compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -80,6 +80,7 @@
|
|||
<!-- no longer available or maintained. Ref: https://spring.io/projects/spring-data-gemfire#overview -->
|
||||
<module>spring-data-geode</module>
|
||||
<module>spring-data-jpa-annotations</module>
|
||||
<module>spring-data-jpa-annotations-2</module>
|
||||
<module>spring-data-jpa-crud</module>
|
||||
<module>spring-data-jpa-crud-2</module>
|
||||
<module>spring-data-jpa-enterprise</module>
|
||||
|
@ -108,7 +109,7 @@
|
|||
<module>spring-jpa-2</module>
|
||||
<module>spring-jdbc</module>
|
||||
<module>spring-jdbc-2</module>
|
||||
<module>spring-jooq</module>
|
||||
<!--<module>spring-jooq</module>-->
|
||||
<module>spring-mybatis</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
<module>spring-data-yugabytedb</module>
|
||||
|
|
|
@ -48,7 +48,7 @@
|
|||
<properties>
|
||||
<maven.release.version>11</maven.release.version>
|
||||
<sirix-core.version>0.9.3</sirix-core.version>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<asm.version>6.1</asm.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -2,4 +2,5 @@
|
|||
- [Patterns for Iterating Over Large Result Sets With Spring Data JPA](https://www.baeldung.com/spring-data-jpa-iterate-large-result-sets)
|
||||
- [Count the Number of Rows in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-row-count)
|
||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- [How To Use findBy() With Multiple Columns in JPA](https://www.baeldung.com/spring-data-jpa-findby-multiple-columns)
|
||||
- More articles: [[<-- prev]](../spring-boot-persistence-2)
|
||||
|
|
|
@ -55,7 +55,6 @@
|
|||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.modelmapper</groupId>
|
||||
|
@ -91,7 +90,6 @@
|
|||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<db.util.version>1.0.7</db.util.version>
|
||||
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<modelmapper.version>3.2.0</modelmapper.version>
|
||||
<commons-codec.version>1.16.1</commons-codec.version>
|
||||
<lombok.version>1.18.30</lombok.version>
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DatabaseViewApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DatabaseViewApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import jakarta.persistence.AttributeOverride;
|
||||
import jakarta.persistence.AttributeOverrides;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.EmbeddedId;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "SHOP_SALE_VIEW")
|
||||
@Getter
|
||||
@Builder
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode(of = {"id"})
|
||||
public class ShopSale {
|
||||
|
||||
@EmbeddedId
|
||||
@AttributeOverrides({
|
||||
@AttributeOverride( name = "shopId", column = @Column(name = "shop_id")),
|
||||
@AttributeOverride( name = "year", column = @Column(name = "transaction_year")),
|
||||
@AttributeOverride( name = "month", column = @Column(name = "transaction_month"))
|
||||
})
|
||||
private ShopSaleCompositeId id;
|
||||
|
||||
@Column(name = "shop_location", length = 100)
|
||||
private String shopLocation;
|
||||
|
||||
@Column(name = "total_amount")
|
||||
private BigDecimal totalAmount;
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class ShopSaleCompositeId {
|
||||
|
||||
private int shopId;
|
||||
|
||||
private int year;
|
||||
|
||||
private int month;
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ShopSaleRepository extends ViewRepository<ShopSale, ShopSaleCompositeId> {
|
||||
|
||||
List<ShopSale> findByIdShopId(Integer shopId);
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "SHOP_SALE_VIEW")
|
||||
@Getter
|
||||
@Builder
|
||||
@ToString
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode(of = {"id"})
|
||||
public class ShopSaleVid {
|
||||
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "shop_id")
|
||||
private int shopId;
|
||||
|
||||
@Column(name = "shop_location", length = 100)
|
||||
private String shopLocation;
|
||||
|
||||
@Column(name = "transaction_year")
|
||||
private int year;
|
||||
|
||||
@Column(name = "transaction_month")
|
||||
private int month;
|
||||
|
||||
@Column(name = "total_amount")
|
||||
private BigDecimal totalAmount;
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ShopSaleVidRepository extends ViewNoIdRepository<ShopSaleVid, Long> {
|
||||
|
||||
List<ShopSaleVid> findByShopId(Integer shopId);
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import org.springframework.data.repository.NoRepositoryBean;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@NoRepositoryBean
|
||||
public interface ViewNoIdRepository<T, K> extends Repository<T, K> {
|
||||
|
||||
long count();
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import org.springframework.data.repository.NoRepositoryBean;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@NoRepositoryBean
|
||||
public interface ViewRepository<T, K> extends Repository<T, K> {
|
||||
|
||||
long count();
|
||||
|
||||
boolean existsById(K id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
List<T> findAllById(Iterable<K> ids);
|
||||
|
||||
Optional<T> findById(K id);
|
||||
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = DatabaseViewApplication.class, properties = {
|
||||
"spring.jpa.show-sql=true",
|
||||
"spring.jpa.properties.hibernate.format_sql=true",
|
||||
"spring.jpa.hibernate.ddl-auto=none",
|
||||
"spring.jpa.defer-datasource-initialization=true",
|
||||
"spring.sql.init.data-locations=classpath:shop-sale-data.sql"
|
||||
})
|
||||
class ShopSaleRepositoryIntegrationTest {
|
||||
|
||||
private static final ShopSaleCompositeId id = ShopSaleCompositeId.builder()
|
||||
.shopId(1)
|
||||
.year(2024)
|
||||
.month(1)
|
||||
.build();
|
||||
|
||||
@Autowired
|
||||
private ShopSaleRepository shopSaleRepository;
|
||||
|
||||
@Test
|
||||
void whenCount_thenValueGreaterThanOne() {
|
||||
assertThat(shopSaleRepository.count()).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindAll_thenReturnAllRecords() {
|
||||
assertThat(shopSaleRepository.findAll()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenExistsById_thenReturnTrue() {
|
||||
assertThat(shopSaleRepository.existsById(id)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindAllById_thenReturnListWithTwoInstances() {
|
||||
assertThat(shopSaleRepository.findAllById(List.of (id))).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindById_thenReturnAnInstance() {
|
||||
assertThat(shopSaleRepository.findById(id).isPresent()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindByShopId_thenReturnAllShopSaleOfThatShop() {
|
||||
var shopId = 1;
|
||||
List<ShopSale> shopSaleVidList = shopSaleRepository.findByIdShopId(shopId);
|
||||
assertThat(shopSaleVidList).isNotEmpty();
|
||||
shopSaleVidList.forEach(s -> assertThat(s.getId().getShopId()).isEqualTo(shopId));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.dbview;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = DatabaseViewApplication.class, properties = {
|
||||
"spring.jpa.show-sql=true",
|
||||
"spring.jpa.properties.hibernate.format_sql=true",
|
||||
"spring.jpa.hibernate.ddl-auto=none",
|
||||
"spring.jpa.defer-datasource-initialization=true",
|
||||
"spring.sql.init.data-locations=classpath:shop-sale-data.sql"
|
||||
})
|
||||
class ShopSaleVidRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ShopSaleVidRepository shopSaleVidRepository;
|
||||
|
||||
@Test
|
||||
void whenCount_thenValueGreaterThanOne() {
|
||||
assertThat(shopSaleVidRepository.count()).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindAll_thenReturnAllRecords() {
|
||||
assertThat(shopSaleVidRepository.findAll()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindByShopId_thenReturnAllShopSaleOfThatShop() {
|
||||
var shopId = 1;
|
||||
List<ShopSaleVid> shopSaleList = shopSaleVidRepository.findByShopId(shopId);
|
||||
assertThat(shopSaleList).isNotEmpty();
|
||||
shopSaleList.forEach(s -> assertThat(s.getShopId()).isEqualTo(shopId));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
CREATE TABLE SHOP
|
||||
(
|
||||
shop_id int AUTO_INCREMENT,
|
||||
shop_location varchar(100) NOT NULL UNIQUE,
|
||||
PRIMARY KEY(shop_id)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE SHOP_TRANSACTION
|
||||
(
|
||||
transaction_id bigint AUTO_INCREMENT,
|
||||
transaction_date date NOT NULL,
|
||||
shop_id int NOT NULL,
|
||||
amount decimal(8,2) NOT NULL,
|
||||
PRIMARY KEY(transaction_id),
|
||||
FOREIGN KEY(shop_id) REFERENCES SHOP(shop_id)
|
||||
);
|
||||
|
||||
|
||||
CREATE VIEW SHOP_SALE_VIEW AS
|
||||
SELECT ROW_NUMBER() OVER () AS id, shop_id, shop_location, transaction_year, transaction_month, SUM(amount) AS total_amount
|
||||
FROM (
|
||||
SELECT shop.shop_id, shop.shop_location, trans.amount, YEAR(transaction_date) AS transaction_year, MONTH(transaction_date) AS transaction_month
|
||||
FROM SHOP shop, SHOP_TRANSACTION trans
|
||||
WHERE shop.shop_id = trans.shop_id
|
||||
) SHOP_MONTH_TRANSACTION
|
||||
GROUP BY shop_id, transaction_year, transaction_month;
|
||||
|
||||
|
||||
INSERT INTO SHOP(shop_location) VALUES ('Ealing');
|
||||
INSERT INTO SHOP(shop_location) VALUES ('Richmond');
|
||||
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-01-05', 1, 3.49);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-01-31', 1, 7.29);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-02-09', 1, 1.60);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-02-17', 1, 5.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-02-18', 1, 5.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-03-01', 1, 8.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-03-22', 1, 5.49);
|
||||
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-01-15', 2, 8.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-01-18', 2, 8.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-02-01', 2, 5.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-02-05', 2, 2.50);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-03-01', 2, 5.99);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-03-02', 2, 6.60);
|
||||
INSERT INTO SHOP_TRANSACTION(transaction_date, shop_id, amount) VALUES ('2024-03-17', 2, 1.19);
|
|
@ -84,7 +84,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<version>3.12.1</version>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
|
|
|
@ -60,7 +60,6 @@
|
|||
<properties>
|
||||
<spring-data-elasticsearch.version>5.1.2</spring-data-elasticsearch.version>
|
||||
<elasticsearch.version>8.9.0</elasticsearch.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,34 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-data-jpa-annotations-2</artifactId>
|
||||
<name>spring-data-jpa-annotations-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.persistence</groupId>
|
||||
<artifactId>jakarta.persistence-api</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.datajpatest;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "app_user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.datajpatest;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class UserApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UserApplication.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.datajpatest;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
User findByUsername(String username);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue