Merge remote-tracking branch 'origin/master'

This commit is contained in:
Philippe Sevestre 2024-02-28 23:51:18 -03:00
commit e7100ab790
321 changed files with 2663 additions and 1271 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,73 @@
package com.baeldung.jsonnodetoarraynode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
public class JsonNodeToArrayNodeConverterUnitTest {
@Test
void givenJsonNode_whenUsingJsonNodeMethods_thenConvertToArrayNode() throws JsonProcessingException {
int count = 0;
String json = "{\"objects\": [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrayNode = new ObjectMapper().readTree(json).get("objects");
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");
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>libraries-data-io-2</artifactId>
<name>libraries-data-io-3</name>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<google-flatbuffers.version>23.5.26</google-flatbuffers.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>${google-flatbuffers.version}</version>
</dependency>
</dependencies>
</project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,9 @@
package com.baeldung.dbview;
import java.util.List;
public interface ShopSaleRepository extends ViewRepository<ShopSale, ShopSaleCompositeId> {
List<ShopSale> findByIdShopId(Integer shopId);
}

View File

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

View File

@ -0,0 +1,9 @@
package com.baeldung.dbview;
import java.util.List;
public interface ShopSaleVidRepository extends ViewNoIdRepository<ShopSaleVid, Long> {
List<ShopSaleVid> findByShopId(Integer shopId);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -74,7 +74,7 @@
</build>
<properties>
<querydsl.version>5.0.0</querydsl.version>
<querydsl.version>5.1.0</querydsl.version>
<mysema.maven.version>1.1.3</mysema.maven.version>
<projectreactor.version>3.5.4</projectreactor.version>
<embed.mongo.version>4.6.3</embed.mongo.version>

13
pom.xml
View File

@ -8,6 +8,9 @@
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>parent-modules</name>
<modules>
<module>libraries-data-io-2</module>
</modules>
<packaging>pom</packaging>
@ -450,7 +453,9 @@
<modules>
<module>apache-spark</module>
<module>jhipster-modules</module>
<module>spring-cloud-modules/spring-cloud-azure</module>
<module>web-modules/restx</module>
<module>libraries-testing</module>
</modules>
</profile>
@ -594,6 +599,7 @@
<module>apache-spark</module>
<module>jhipster-modules</module>
<module>spring-cloud-modules/spring-cloud-azure</module>
<module>web-modules/restx</module>
</modules>
@ -758,7 +764,6 @@
<module>libraries-server-2</module>
<module>libraries-server</module>
<module>libraries-stream</module>
<module>libraries-testing</module>
<module>libraries-testing-2</module>
<module>libraries-transform</module>
<module>libraries</module> <!-- very long running -->
@ -808,7 +813,6 @@
<module>spring-batch</module>
<module>spring-boot-modules</module>
<module>spring-boot-rest</module>
<module>spring-cloud-modules/spring-cloud-azure</module>
<module>spring-cloud-modules/spring-cloud-circuit-breaker</module>
<module>spring-cloud-modules/spring-cloud-contract</module>
<!--<module>spring-cloud-modules/spring-cloud-data-flow</module>--><!-- failing after upgrading to jdk17-->
@ -1054,7 +1058,6 @@
<module>spring-batch</module>
<module>spring-boot-modules</module>
<module>spring-boot-rest</module>
<module>spring-cloud-modules/spring-cloud-azure</module>
<module>spring-cloud-modules/spring-cloud-circuit-breaker</module>
<module>spring-cloud-modules/spring-cloud-contract</module>
<!--<module>spring-cloud-modules/spring-cloud-data-flow</module>--><!-- failing after upgrading to jdk17-->
@ -1184,9 +1187,9 @@
<jmh-generator.version>1.37</jmh-generator.version>
<maven-failsafe-plugin.version>3.1.2</maven-failsafe-plugin.version>
<commons-collections4.version>4.4</commons-collections4.version>
<commons-io.version>2.13.0</commons-io.version>
<commons-io.version>2.15.1</commons-io.version>
<commons-lang3.version>3.14.0</commons-lang3.version>
<commons-cli.version>1.5.0</commons-cli.version>
<commons-cli.version>1.6.0</commons-cli.version>
<maven-war-plugin.version>3.4.0</maven-war-plugin.version>
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
<jstl-api.version>1.2</jstl-api.version>

View File

@ -128,7 +128,7 @@
</profiles>
<properties>
<compiler-plugin.version>3.10.1</compiler-plugin.version>
<compiler-plugin.version>3.12.1</compiler-plugin.version>
<failsafe.useModulePath>false</failsafe.useModulePath>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -27,7 +27,7 @@
</dependencyManagement>
<properties>
<compiler-plugin.version>3.11.0</compiler-plugin.version>
<compiler-plugin.version>3.12.1</compiler-plugin.version>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

View File

@ -136,7 +136,7 @@
</profiles>
<properties>
<compiler-plugin.version>3.10.1</compiler-plugin.version>
<compiler-plugin.version>3.12.1</compiler-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>

View File

@ -17,7 +17,7 @@
<module>apache-shiro</module>
<module>cas</module>
<module>cloud-foundry-uaa</module>
<module>java-ee-8-security-api</module>
<!-- <module>java-ee-8-security-api</module>-->
<module>jee-7-security</module>
<module>jjwt</module>
<module>jwt</module>

View File

@ -11,16 +11,16 @@
<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>
<module>spring-boot-admin</module>
<module>spring-boot-angular</module>
<module>spring-boot-annotations</module>
<module>spring-boot-annotations-2</module>
<!-- <module>spring-boot-annotations-2</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-artifacts</module>
<module>spring-boot-artifacts-2</module>
<module>spring-boot-autoconfiguration</module>
@ -31,33 +31,33 @@
<module>spring-boot-config-jpa-error</module>
<module>spring-boot-ctx-fluent</module>
<module>spring-boot-deployment</module>
<module>spring-boot-di</module>
<!-- <module>spring-boot-di</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-disable-logging</module>
<module>spring-boot-ci-cd</module>
<!-- <module>spring-boot-cli</module> --> <!-- Not a maven project -->
<module>spring-boot-custom-starter</module>
<!-- <module>spring-boot-custom-starter</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-crud</module>
<module>spring-boot-data</module>
<module>spring-boot-environment</module>
<module>spring-boot-exceptions</module>
<module>spring-boot-flowable</module>
<module>spring-boot-graphql</module>
<!-- <module>spring-boot-graphql</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!--<module>spring-boot-groovy</module>--> <!-- failing after upgrading to jdk17-->
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-jasypt</module>
<module>spring-boot-jsp</module>
<!-- <module>spring-boot-jsp</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-keycloak</module>
<module>spring-boot-keycloak-2</module>
<module>spring-boot-libraries</module>
<module>spring-boot-libraries-2</module>
<!-- <module>spring-boot-libraries</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-libraries-2</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-process-automation</module>
<module>spring-boot-logging-logback</module>
<module>spring-boot-logging-log4j2</module>
<module>spring-boot-mvc</module>
<!-- <module>spring-boot-mvc</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-mvc-2</module>
<module>spring-boot-mvc-3</module>
<module>spring-boot-mvc-4</module>
<module>spring-boot-mvc-5</module>
<!-- <module>spring-boot-mvc-5</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-mvc-birt</module>
<module>spring-boot-mvc-jersey</module>
<module>spring-boot-nashorn</module>
@ -65,34 +65,34 @@
<module>spring-boot-performance</module>
<module>spring-boot-property-exp</module>
<module>spring-boot-request-params</module>
<module>spring-boot-runtime</module>
<module>spring-boot-runtime-2</module>
<!-- <module>spring-boot-runtime</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-runtime-2</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-security</module>
<module>spring-boot-security-2</module>
<module>spring-boot-ssl-bundles</module>
<module>spring-boot-telegram</module>
<module>spring-boot-springdoc</module>
<module>spring-boot-swagger</module>
<module>spring-boot-swagger-2</module>
<!-- <module>spring-boot-springdoc</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-swagger</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-swagger-2</module>--> <!-- failing after upgrading to spring boot 3. Swagger codegen yet not compatible?!-->
<module>spring-boot-swagger-jwt</module>
<module>spring-boot-swagger-keycloak</module>
<module>spring-boot-swagger-springfox</module>
<module>spring-boot-testing</module>
<module>spring-boot-testing-2</module>
<!-- <module>spring-boot-testing</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-testing-2</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-testing-spock</module>
<module>spring-boot-vue</module>
<module>spring-boot-actuator</module>
<module>spring-boot-data-2</module>
<module>spring-boot-validation</module>
<module>spring-boot-data-3</module>
<module>spring-caching</module>
<module>spring-caching-2</module>
<module>spring-boot-redis</module>
<!-- <module>spring-boot-data-3</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-caching</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-caching-2</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<!-- <module>spring-boot-redis</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-cassandre</module>
<module>spring-boot-react</module>
<!-- <module>spring-boot-react</module>--> <!-- failing after upgrading to spring boot 3.2.x. very old node version which is not available now. -->
<!-- <module>spring-boot-3</module> --> <!-- JAVA-20931 -->
<module>spring-boot-3-grpc</module>
<module>spring-boot-3-native</module>
<!-- <module>spring-boot-3-native</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-3-observation</module>
<module>spring-boot-3-test-pitfalls</module>
<module>spring-boot-3-testcontainers</module>
@ -100,10 +100,10 @@
<module>spring-boot-resilience4j</module>
<module>spring-boot-properties</module>
<module>spring-boot-properties-2</module>
<module>spring-boot-properties-3</module>
<!-- <module>spring-boot-properties-3</module>--> <!-- failing after upgrading to spring boot 3.2.x -->
<module>spring-boot-properties-4</module>
<module>spring-boot-properties-migrator-demo</module>
<module>spring-boot-aws</module>
<module>spring-boot-aws</module> <!-- This project is Spring Boot 2 and cannot be updated -->
<module>spring-boot-keycloak-adapters</module>
<module>spring-boot-mvc-legacy</module>
<module>spring-boot-springdoc-2</module>

View File

@ -8,10 +8,9 @@
<name>helloworld-grpc-consumer</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-3-grpc</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -28,7 +27,6 @@
</dependencies>
<properties>
<spring-boot.version>3.2.0</spring-boot.version>
<grpc-spring-boot-starter.version>2.15.0.RELEASE</grpc-spring-boot-starter.version>
</properties>

View File

@ -84,6 +84,7 @@
<os-maven-plugin.version>1.7.1</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
<annotation-api.version>1.3.2</annotation-api.version>
<spring-boot.repackage.skip>true</spring-boot.repackage.skip>
</properties>
</project>

View File

@ -8,10 +8,9 @@
<name>helloworld-grpc-provider</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-3-grpc</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -28,7 +27,6 @@
</dependencies>
<properties>
<spring-boot.version>3.2.0</spring-boot.version>
<grpc-spring-boot-starter.version>2.15.0.RELEASE</grpc-spring-boot-starter.version>
</properties>

View File

@ -3,17 +3,15 @@
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>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-3-grpc</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>spring-boot-3-grpc</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modules>

View File

@ -9,10 +9,9 @@
<description>Demo project for Spring Boot</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -100,6 +99,7 @@
<springdoc.version>2.0.0</springdoc.version>
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
<native.maven.plugin.version>0.9.17</native.maven.plugin.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -8,10 +8,9 @@
<description>Demo project for Spring Boot 3 Observation</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -109,6 +108,7 @@
<properties>
<start-class>com.baeldung.samples.SimpleObservationApplication</start-class>
<p6spy-spring-boot-starter.version>1.9.0</p6spy-spring-boot-starter.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -9,10 +9,9 @@
<description>Demo project for Spring Boot Testing Pitfalls</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -82,6 +81,7 @@
<org.mapstruct.version>1.5.3.Final</org.mapstruct.version>
<lombok-mapstruct-binding.version>0.2.0</lombok-mapstruct-binding.version>
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -9,10 +9,9 @@
<description>Testcontainer Improvements in Spring Boot 3</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -96,6 +95,7 @@
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
<testcontainers.version>1.18.3</testcontainers.version>
<rest-assured.version>5.3.1</rest-assured.version>
<java.version>17</java.version>
</properties>
</project>

View File

@ -9,10 +9,9 @@
<description>URL Matching in Spring Boot 3</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -46,7 +45,6 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -94,7 +92,6 @@
</build>
<properties>
<spring-test.version>6.0.6</spring-test.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<reactor-core.version>3.6.0</reactor-core.version>
<reactor-test.version>3.6.0></reactor-test.version>

View File

@ -9,10 +9,9 @@
<description>This is simple boot application for Spring boot actuator test</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -25,13 +25,13 @@
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>${spring-boot-admin-server.version}</version>
<version>${spring-boot.version}</version>
</dependency>
<!--Add login page and logout feature -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-login</artifactId>
<version>${spring-boot-admin-server-ui-login.version}</version>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -45,7 +45,7 @@
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin-starter-client.version}</version>
<version>${spring-boot.version}</version>
</dependency>
<!--mail notifications -->
<dependency>
@ -69,16 +69,8 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<spring-boot-admin-server.version>2.4.1</spring-boot-admin-server.version>
<spring-boot-admin-starter-client.version>2.4.1</spring-boot-admin-starter-client.version>
<spring-boot-admin-server-ui-login.version>1.5.7</spring-boot-admin-server-ui-login.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
</properties>
</project>

View File

@ -5,6 +5,7 @@ import java.util.UUID;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@ -17,6 +18,7 @@ import de.codecentric.boot.admin.server.config.AdminServerProperties;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
private final AdminServerProperties adminServer;
public WebSecurityConfig(AdminServerProperties adminServer) {
@ -29,32 +31,24 @@ public class WebSecurityConfig {
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.getContextPath() + "/");
http.authorizeRequests()
.antMatchers(this.adminServer.getContextPath() + "/assets/**")
.permitAll()
.antMatchers(this.adminServer.getContextPath() + "/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage(this.adminServer.getContextPath() + "/login")
.successHandler(successHandler)
.and()
.logout()
.logoutUrl(this.adminServer.getContextPath() + "/logout")
.and()
.httpBasic()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances", HttpMethod.POST.toString()), new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances/*", HttpMethod.DELETE.toString()),
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/actuator/**"))
.and()
.rememberMe()
.key(UUID.randomUUID()
.toString())
.tokenValiditySeconds(1209600);
http.authorizeHttpRequests(req -> req.requestMatchers(this.adminServer.getContextPath() + "/assets/**")
.permitAll()
.requestMatchers(this.adminServer.getContextPath() + "/login")
.permitAll()
.anyRequest()
.authenticated())
.formLogin(formLogin -> formLogin.loginPage(this.adminServer.getContextPath() + "/login")
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminServer.getContextPath() + "/logout"))
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances", HttpMethod.POST.toString()),
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/instances/*", HttpMethod.DELETE.toString()),
new AntPathRequestMatcher(this.adminServer.getContextPath() + "/actuator/**")))
.rememberMe(rememberMe -> rememberMe.key(UUID.randomUUID()
.toString())
.tokenValiditySeconds(1209600));
return http.build();
}
}

View File

@ -52,7 +52,7 @@ public class WebSecurityConfigIntegrationTest {
.password("admin"));
mockMvc
.perform(get("/applications/"))
.perform(get("/applications"))
.andExpect(status().is2xxSuccessful());
}

View File

@ -49,4 +49,8 @@
</plugins>
</build>
<properties>
<start-class>com.baeldung.Application</start-class>
</properties>
</project>

View File

@ -1,9 +1,9 @@
package com.baeldung.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {

View File

@ -1,5 +1,22 @@
package com.baeldung.ecommerce.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.baeldung.ecommerce.dto.OrderProductDto;
import com.baeldung.ecommerce.exception.ResourceNotFoundException;
import com.baeldung.ecommerce.model.Order;
@ -8,18 +25,8 @@ import com.baeldung.ecommerce.model.OrderStatus;
import com.baeldung.ecommerce.service.OrderProductService;
import com.baeldung.ecommerce.service.OrderService;
import com.baeldung.ecommerce.service.ProductService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import jakarta.validation.constraints.NotNull;
@RestController
@RequestMapping("/api/orders")

View File

@ -1,12 +1,13 @@
package com.baeldung.ecommerce.controller;
import com.baeldung.ecommerce.model.Product;
import com.baeldung.ecommerce.service.ProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
import com.baeldung.ecommerce.model.Product;
import com.baeldung.ecommerce.service.ProductService;
import jakarta.validation.constraints.NotNull;
@RestController
@RequestMapping("/api/products")

View File

@ -6,8 +6,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,16 +1,22 @@
package com.baeldung.ecommerce.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import jakarta.validation.Valid;
@Entity
@Table(name = "orders")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="orderProducts")

View File

@ -2,10 +2,10 @@ package com.baeldung.ecommerce.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Transient;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
@Entity
public class OrderProduct {

View File

@ -1,13 +1,14 @@
package com.baeldung.ecommerce.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import jakarta.persistence.Embeddable;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Embeddable
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "order")

View File

@ -1,7 +1,11 @@
package com.baeldung.ecommerce.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import jakarta.persistence.Basic;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotNull;
@Entity
public class Product {

View File

@ -1,10 +1,11 @@
package com.baeldung.ecommerce.service;
import com.baeldung.ecommerce.model.OrderProduct;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.baeldung.ecommerce.model.OrderProduct;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@Validated
public interface OrderProductService {

View File

@ -1,10 +1,11 @@
package com.baeldung.ecommerce.service;
import com.baeldung.ecommerce.model.Order;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.baeldung.ecommerce.model.Order;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@Validated
public interface OrderService {

View File

@ -1,10 +1,11 @@
package com.baeldung.ecommerce.service;
import com.baeldung.ecommerce.model.Product;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.baeldung.ecommerce.model.Product;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
@Validated
public interface ProductService {

View File

@ -1,37 +1,37 @@
package com.baeldung.ecommerce;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.baeldung.ecommerce.controller.OrderController;
import com.baeldung.ecommerce.controller.ProductController;
import com.baeldung.ecommerce.dto.OrderProductDto;
import com.baeldung.ecommerce.model.Order;
import com.baeldung.ecommerce.model.Product;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { EcommerceApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EcommerceApplicationIntegrationTest {
@Autowired private TestRestTemplate restTemplate;
@LocalServerPort private int port;
@LocalServerPort
private int port;
@Autowired private ProductController productController;
@ -80,9 +80,7 @@ public class EcommerceApplicationIntegrationTest {
public void givenPostOrder_whenBodyRequestMatcherJson_thenResponseContainsEqualObjectProperties() {
final ResponseEntity<Order> postResponse = restTemplate.postForEntity("http://localhost:" + port + "/api/orders", prepareOrderForm(), Order.class);
Order order = postResponse.getBody();
Assertions
.assertThat(postResponse.getStatusCode())
.isEqualByComparingTo(HttpStatus.CREATED);
assertEquals(HttpStatus.CREATED, postResponse.getStatusCode());
assertThat(order, hasProperty("status", is("PAID")));
assertThat(order.getOrderProducts(), hasItem(hasProperty("quantity", is(2))));

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