Merge branch 'eugenp:master' into master

This commit is contained in:
JoannaaKL
2021-09-20 10:06:38 +02:00
committed by GitHub
176 changed files with 2711 additions and 787 deletions
+1 -1
View File
@@ -50,4 +50,4 @@
<commons-codec.version>1.11</commons-codec.version>
</properties>
</project>
</project>
@@ -29,11 +29,13 @@ public class Graph {
stack.push(start);
while (!stack.isEmpty()) {
int current = stack.pop();
isVisited[current] = true;
visit(current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
stack.push(dest);
if(!isVisited[current]){
isVisited[current] = true;
visit(current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
stack.push(dest);
}
}
}
}
+5 -1
View File
@@ -133,6 +133,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
@@ -196,7 +201,6 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
<beam.version>2.19.0</beam.version>
<assertj.version>3.9.0</assertj.version>
<bval.version>1.1.2</bval.version>
@@ -10,7 +10,6 @@ import com.baeldung.apache.beam.intro.WordCount;
public class WordCountUnitTest {
@Test
// @Ignore
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
assertTrue(jobDone);
-3
View File
@@ -32,7 +32,6 @@
<!-- Uncomment this to add support for file uploads: -->
<!-- <dependency> <groupId>org.apache.tapestry</groupId> <artifactId>tapestry-upload</artifactId>
<version>${tapestry-release-version}</version> </dependency> -->
<!-- A dependency on either JUnit or TestNG is required, or the surefire plugin (which runs the
tests) will fail, preventing Maven from packaging the WAR. Tapestry includes a large number of testing
facilities designed for use with TestNG (http://testng.org/), so it's recommended. -->
@@ -110,8 +109,6 @@
</plugins>
</build>
<reporting />
<repositories>
<repository>
<id>jboss</id>
+1 -2
View File
@@ -29,7 +29,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${org.slf4j.slf4j-simple.version}</version>
<version>${org.slf4j.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -61,7 +61,6 @@
<properties>
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
<org.slf4j.slf4j-simple.version>1.7.12</org.slf4j.slf4j-simple.version>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
</properties>
+1 -1
View File
@@ -93,5 +93,5 @@
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.10.27</awssdk.version>
</properties>
</project>
-1
View File
@@ -166,7 +166,6 @@
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<groovy-wslite.version>1.1.3</groovy-wslite.version>
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>
<assembly.plugin.version>3.1.0</assembly.plugin.version>
<compiler.plugin.version>3.8.0</compiler.plugin.version>
+52 -52
View File
@@ -1,60 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-12</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-12</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-12</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-12</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
<properties>
<maven.compiler.source.version>12</maven.compiler.source.version>
<maven.compiler.target.version>12</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
+2 -2
View File
@@ -14,7 +14,7 @@
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
@@ -35,7 +35,7 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
+1
View File
@@ -1,3 +1,4 @@
### Relevant articles:
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
+45 -45
View File
@@ -1,53 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-16</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-16</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-16</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-16</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>16</maven.compiler.source.version>
<maven.compiler.target.version>16</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
<properties>
<maven.compiler.source.version>16</maven.compiler.source.version>
<maven.compiler.target.version>16</maven.compiler.target.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
@@ -0,0 +1,128 @@
package com.baeldung.streams;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class StreamToListComparisonWithCollectorsToListUnitTest {
@Test
public void whenAddingtoCollectToList_thenSuccess() {
List<String> result = Stream.of(Locale.getISOCountries())
.collect(Collectors.toList());
Assertions.assertDoesNotThrow(() -> {
result.add("test");
});
}
@Test
public void whenSortingtoCollectToList_thenSuccess() {
List<String> result = Stream.of(Locale.getISOCountries())
.collect(Collectors.toList());
Assertions.assertDoesNotThrow(() -> {
result.sort(String::compareToIgnoreCase);
});
}
@Test
public void whenAddingCollectUnmodifiableToList_thenException() {
List<String> result = Stream.of(Locale.getISOCountries())
.collect(Collectors.toUnmodifiableList());
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
result.add("test");
});
}
@Test
public void whenSortingCollectUnmodifiableToList_thenSortException() {
List<String> result = Stream.of(Locale.getISOCountries())
.collect(Collectors.toUnmodifiableList());
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
result.sort(String::compareToIgnoreCase);
});
}
@Test
public void whenAddingStreamToList_thenException() {
List<String> result = Stream.of(Locale.getISOCountries())
.toList();
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
result.add("test");
});
}
@Test
public void whenSortingStreamToList_thenException() {
List<String> result = Stream.of(Locale.getISOCountries())
.toList();
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
result.sort(String::compareToIgnoreCase);
});
}
@Test
public void whenComparingStreamToList_withCollectToList_thenEqual() {
List<String> streamToList = Stream.of(Locale.getISOCountries())
.toList();
List<String> collectToList = Stream.of(Locale.getISOCountries())
.collect(Collectors.toList());
Assertions.assertEquals(streamToList, collectToList);
}
@Test
public void whenComparingStreamToList_withUnmodifiedCollectToList_thenEqual() {
List<String> streamToList = Stream.of(Locale.getISOCountries())
.toList();
List<String> collectToUnmodifiableList = Stream.of(Locale.getISOCountries())
.collect(Collectors.toUnmodifiableList());
Assertions.assertEquals(streamToList, collectToUnmodifiableList);
}
@Test
public void whenNullCollectorsToList_thenSuccess() {
Assertions.assertDoesNotThrow(() -> {
Stream.of(null, null)
.collect(Collectors.toList());
});
}
@Test
public void whenNullCollectorsUnmodifiableToList_thenException() {
Assertions.assertThrows(NullPointerException.class, () -> {
Stream.of(null, null)
.collect(Collectors.toUnmodifiableList());
});
}
@Test
public void whenNullStreamToList_thenSuccess() {
Assertions.assertDoesNotThrow(() -> {
Stream.of(null, null)
.toList();
});
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -7,7 +7,7 @@
<version>${project.parent.version}</version>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -7,7 +7,7 @@
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
+1 -1
View File
@@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -39,7 +39,7 @@
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>incubator-features</id>
@@ -131,7 +131,7 @@
</build>
</profile>
</profiles>
<build>
<finalName>core-java-9-new-features</finalName>
<plugins>
@@ -10,3 +10,4 @@ This module contains articles about advanced operations on arrays in Java. They
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)
- [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays)
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
@@ -78,4 +78,5 @@
<guava.version>28.2-jre</guava.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
+1 -1
View File
@@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-char</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -6,7 +6,7 @@
<artifactId>core-java-collections-2</artifactId>
<name>core-java-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -1,31 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.19.0</assertj.version>
</properties>
<properties>
<assertj.version>3.19.0</assertj.version>
</properties>
</project>
@@ -33,5 +33,5 @@
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
</project>
@@ -7,7 +7,7 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
@@ -26,7 +26,6 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -36,4 +36,5 @@
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
@@ -0,0 +1,21 @@
// The next line is commented out to avoid the code to fail the build.
// package com.baeldung;
/**
* If the below package declaration is commented out and the above incorrect package
* declaration is uncommented, then the problem will replicate.
*/
package com.baeldung.bookstore;
public class Book {
private String title;
private String author;
private long isbn;
public Book(String title, String author, long isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.bookstore;
import java.util.Random;
public class LibraryAdmin {
public Book createBook(String title, String author) {
final long isbn = new Random().nextLong();
return new Book(title, author, isbn);
}
}
@@ -25,6 +25,7 @@
<version>${commons-codec.version}</version>
</dependency>
</dependencies>
<properties>
<commons-codec.version>1.15</commons-codec.version>
</properties>
@@ -8,4 +8,5 @@ This module contains articles about networking in Java
- [Downloading Email Attachments in Java](https://www.baeldung.com/java-download-email-attachments)
- [Connection Timeout vs. Read Timeout for Java Sockets](https://www.baeldung.com/java-socket-connection-read-timeout)
- [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range)
- [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address)
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
@@ -5,4 +5,5 @@ This module contains articles about core Java Security
### Relevant Articles:
- [Secret Key and String Conversion in Java](https://www.baeldung.com/java-secret-key-to-string)
- [Enabling Unlimited Strength Cryptography in Java](https://www.baeldung.com/jce-enable-unlimited-strength)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
@@ -0,0 +1,17 @@
package com.baeldung.cryptography;
import org.junit.Test;
import java.security.NoSuchAlgorithmException;
import static org.assertj.core.api.Assertions.assertThat;
public class CryptographyStrengthUnitTest {
private static final int UNLIMITED_KEY_SIZE = 2147483647;
@Test
public void whenDefaultCheck_thenUnlimitedReturned() throws NoSuchAlgorithmException {
int maxKeySize = javax.crypto.Cipher.getMaxAllowedKeyLength("AES");
assertThat(maxKeySize).isEqualTo(UNLIMITED_KEY_SIZE);
}
}
+1
View File
@@ -137,4 +137,5 @@
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>
+2 -3
View File
@@ -39,12 +39,12 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.datavec/datavec-api -->
<dependency>
@@ -62,7 +62,6 @@
<properties>
<dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version -->
<httpclient.version>4.3.5</httpclient.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
</project>
+1 -3
View File
@@ -99,7 +99,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
@@ -204,8 +204,6 @@
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
<mockito.version>2.21.0</mockito.version>
<jsonpath.version>2.4.0</jsonpath.version>
<logback.version>1.2.3</logback.version>
<slf4j.version>1.7.25</slf4j.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<compiler.plugin.version>3.1</compiler.plugin.version>
</properties>
+76 -75
View File
@@ -1,81 +1,82 @@
<?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>grpc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>grpc</name>
<packaging>jar</packaging>
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>grpc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>grpc</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os-maven-plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
<protocArtifact>
com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<io.grpc.version>1.16.1</io.grpc.version>
<os-maven-plugin.version>1.6.1</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<scope>runtime</scope>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os-maven-plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${io.grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<io.grpc.version>1.40.1</io.grpc.version>
<protoc.version>3.17.2</protoc.version>
<os-maven-plugin.version>1.6.2</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
</properties>
</project>
@@ -0,0 +1,183 @@
package com.baeldung.grpc.streaming;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.baeldung.grpc.streaming.StockQuoteProviderGrpc.StockQuoteProviderBlockingStub;
import com.baeldung.grpc.streaming.StockQuoteProviderGrpc.StockQuoteProviderStub;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
public class StockClient {
private static final Logger logger = Logger.getLogger(StockClient.class.getName());
private final StockQuoteProviderBlockingStub blockingStub;
private final StockQuoteProviderStub nonBlockingStub;
private List<Stock> stocks;
public StockClient(Channel channel) {
blockingStub = StockQuoteProviderGrpc.newBlockingStub(channel);
nonBlockingStub = StockQuoteProviderGrpc.newStub(channel);
initializeStocks();
}
public void serverSideStreamingListOfStockPrices() {
logInfo("######START EXAMPLE######: ServerSideStreaming - list of Stock prices from a given stock");
Stock request = Stock.newBuilder()
.setTickerSymbol("AU")
.setCompanyName("Austich")
.setDescription("server streaming example")
.build();
Iterator<StockQuote> stockQuotes;
try {
logInfo("REQUEST - ticker symbol {0}", request.getTickerSymbol());
stockQuotes = blockingStub.serverSideStreamingGetListStockQuotes(request);
for (int i = 1; stockQuotes.hasNext(); i++) {
StockQuote stockQuote = stockQuotes.next();
logInfo("RESPONSE - Price #" + i + ": {0}", stockQuote.getPrice());
}
} catch (StatusRuntimeException e) {
logInfo("RPC failed: {0}", e.getStatus());
}
}
public void clientSideStreamingGetStatisticsOfStocks() throws InterruptedException {
logInfo("######START EXAMPLE######: ClientSideStreaming - getStatisticsOfStocks from a list of stocks");
final CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<StockQuote> responseObserver = new StreamObserver<StockQuote>() {
@Override
public void onNext(StockQuote summary) {
logInfo("RESPONSE, got stock statistics - Average Price: {0}, description: {1}", summary.getPrice(), summary.getDescription());
}
@Override
public void onCompleted() {
logInfo("Finished clientSideStreamingGetStatisticsOfStocks");
finishLatch.countDown();
}
@Override
public void onError(Throwable t) {
logWarning("Stock Statistics Failed: {0}", Status.fromThrowable(t));
finishLatch.countDown();
}
};
StreamObserver<Stock> requestObserver = nonBlockingStub.clientSideStreamingGetStatisticsOfStocks(responseObserver);
try {
for (Stock stock : stocks) {
logInfo("REQUEST: {0}, {1}", stock.getTickerSymbol(), stock.getCompanyName());
requestObserver.onNext(stock);
if (finishLatch.getCount() == 0) {
return;
}
}
} catch (RuntimeException e) {
requestObserver.onError(e);
throw e;
}
requestObserver.onCompleted();
if (!finishLatch.await(1, TimeUnit.MINUTES)) {
logWarning("clientSideStreamingGetStatisticsOfStocks can not finish within 1 minutes");
}
}
public void bidirectionalStreamingGetListsStockQuotes() throws InterruptedException{
logInfo("#######START EXAMPLE#######: BidirectionalStreaming - getListsStockQuotes from list of stocks");
final CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<StockQuote> responseObserver = new StreamObserver<StockQuote>() {
@Override
public void onNext(StockQuote stockQuote) {
logInfo("RESPONSE price#{0} : {1}, description:{2}", stockQuote.getOfferNumber(), stockQuote.getPrice(), stockQuote.getDescription());
}
@Override
public void onCompleted() {
logInfo("Finished bidirectionalStreamingGetListsStockQuotes");
finishLatch.countDown();
}
@Override
public void onError(Throwable t) {
logWarning("bidirectionalStreamingGetListsStockQuotes Failed: {0}", Status.fromThrowable(t));
finishLatch.countDown();
}
};
StreamObserver<Stock> requestObserver = nonBlockingStub.bidirectionalStreamingGetListsStockQuotes(responseObserver);
try {
for (Stock stock : stocks) {
logInfo("REQUEST: {0}, {1}", stock.getTickerSymbol(), stock.getCompanyName());
requestObserver.onNext(stock);
Thread.sleep(200);
if (finishLatch.getCount() == 0) {
return;
}
}
} catch (RuntimeException e) {
requestObserver.onError(e);
throw e;
}
requestObserver.onCompleted();
if (!finishLatch.await(1, TimeUnit.MINUTES)) {
logWarning("bidirectionalStreamingGetListsStockQuotes can not finish within 1 minute");
}
}
public static void main(String[] args) throws InterruptedException {
String target = "localhost:8980";
if (args.length > 0) {
target = args[0];
}
ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
.usePlaintext()
.build();
try {
StockClient client = new StockClient(channel);
client.serverSideStreamingListOfStockPrices();
client.clientSideStreamingGetStatisticsOfStocks();
client.bidirectionalStreamingGetListsStockQuotes();
} finally {
channel.shutdownNow()
.awaitTermination(5, TimeUnit.SECONDS);
}
}
private void initializeStocks() {
this.stocks = Arrays.asList(Stock.newBuilder().setTickerSymbol("AU").setCompanyName("Auburn Corp").setDescription("Aptitude Intel").build()
, Stock.newBuilder().setTickerSymbol("BAS").setCompanyName("Bassel Corp").setDescription("Business Intel").build()
, Stock.newBuilder().setTickerSymbol("COR").setCompanyName("Corvine Corp").setDescription("Corporate Intel").build()
, Stock.newBuilder().setTickerSymbol("DIA").setCompanyName("Dialogic Corp").setDescription("Development Intel").build()
, Stock.newBuilder().setTickerSymbol("EUS").setCompanyName("Euskaltel Corp").setDescription("English Intel").build());
}
private void logInfo(String msg, Object... params) {
logger.log(Level.INFO, msg, params);
}
private void logWarning(String msg, Object... params) {
logger.log(Level.WARNING, msg, params);
}
}
@@ -0,0 +1,147 @@
package com.baeldung.grpc.streaming;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
public class StockServer {
private static final Logger logger = Logger.getLogger(StockServer.class.getName());
private final int port;
private final Server server;
public StockServer(int port) throws IOException {
this.port = port;
server = ServerBuilder.forPort(port)
.addService(new StockService())
.build();
}
public void start() throws IOException {
server.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime()
.addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("shutting down server");
try {
StockServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("server shutted down");
}
});
}
public void stop() throws InterruptedException {
if (server != null) {
server.shutdown()
.awaitTermination(30, TimeUnit.SECONDS);
}
}
public static void main(String[] args) throws Exception {
StockServer stockServer = new StockServer(8980);
stockServer.start();
if (stockServer.server != null) {
stockServer.server.awaitTermination();
}
}
private static class StockService extends StockQuoteProviderGrpc.StockQuoteProviderImplBase {
StockService() {
}
@Override
public void serverSideStreamingGetListStockQuotes(Stock request, StreamObserver<StockQuote> responseObserver) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request))
.setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
responseObserver.onCompleted();
}
@Override
public StreamObserver<Stock> clientSideStreamingGetStatisticsOfStocks(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
int count;
double price = 0.0;
StringBuffer sb = new StringBuffer();
@Override
public void onNext(Stock stock) {
count++;
price = +fetchStockPriceBid(stock);
sb.append(":")
.append(stock.getTickerSymbol());
}
@Override
public void onCompleted() {
responseObserver.onNext(StockQuote.newBuilder()
.setPrice(price / count)
.setDescription("Statistics-" + sb.toString())
.build());
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.log(Level.WARNING, "error:{0}", t.getMessage());
}
};
}
@Override
public StreamObserver<Stock> bidirectionalStreamingGetListsStockQuotes(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
@Override
public void onNext(Stock request) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request))
.setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.log(Level.WARNING, "error:{0}", t.getMessage());
}
};
}
}
private static double fetchStockPriceBid(Stock stock) {
return stock.getTickerSymbol()
.length()
+ ThreadLocalRandom.current()
.nextDouble(-0.1d, 0.1d);
}
}
+31
View File
@@ -0,0 +1,31 @@
syntax = "proto3";
package stockquote;
option java_multiple_files = true;
option java_package = "com.baeldung.grpc.streaming";
option java_outer_classname = "StockQuoteProto";
option objc_class_prefix = "RTG";
//basic setup ...
service StockQuoteProvider {
rpc serverSideStreamingGetListStockQuotes(Stock) returns (stream StockQuote) {}
rpc clientSideStreamingGetStatisticsOfStocks(stream Stock) returns (StockQuote) {}
rpc bidirectionalStreamingGetListsStockQuotes(stream Stock) returns (stream StockQuote) {}
}
message Stock {
string ticker_symbol = 1;
string company_name = 2;
string description = 3;
}
message StockQuote {
double price = 1;
int32 offer_number = 2;
string description = 3;
}
@@ -24,7 +24,7 @@
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-datatype.version}</version>
<version>${jackson.version}</version>
</dependency>
<!-- CSV -->
<dependency>
@@ -52,7 +52,6 @@
<properties>
<assertj.version>3.11.0</assertj.version>
<jackson-datatype.version>2.9.8</jackson-datatype.version>
</properties>
</project>
@@ -1,14 +1,22 @@
package com.baeldung.jackson.inheritance;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Car;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Fleet;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Truck;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Vehicle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class SubTypeHandlingUnitTest {
@Test
@@ -23,21 +31,30 @@ public class SubTypeHandlingUnitTest {
}
@Test
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
Car car = new Car("Mercedes-Benz", "S500", 5, 250.0);
Truck truck = new Truck("Isuzu", "NQR", 7500.0);
SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0);
List<SubTypeConstructorStructure.Vehicle> vehicles = new ArrayList<>();
List<Vehicle> vehicles = new ArrayList<>();
vehicles.add(car);
vehicles.add(truck);
SubTypeConstructorStructure.Fleet serializedFleet = new SubTypeConstructorStructure.Fleet();
Fleet serializedFleet = new Fleet();
serializedFleet.setVehicles(vehicles);
String jsonDataString = mapper.writeValueAsString(serializedFleet);
mapper.readValue(jsonDataString, SubTypeConstructorStructure.Fleet.class);
mapper.readValue(jsonDataString, Fleet.class);
Fleet deserializedFleet = mapper.readValue(jsonDataString, Fleet.class);
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(Car.class));
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(Truck.class));
}
}
@@ -10,12 +10,18 @@ import java.util.ArrayList;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class TypeInfoInclusionUnitTest {
@Test
public void givenTypeInfo_whenAnnotatingGlobally_thenTypesAreCorrectlyRecovered() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
TypeInfoStructure.Car car = new TypeInfoStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
TypeInfoStructure.Truck truck = new TypeInfoStructure.Truck("Isuzu", "NQR", 7500.0);
-5
View File
@@ -21,13 +21,11 @@
<artifactId>activeweb</artifactId>
<version>${activeweb.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.java.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
@@ -35,14 +33,12 @@
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>activeweb-testing</artifactId>
<version>${activeweb-testing.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -73,7 +69,6 @@
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>activejdbc-instrumentation</artifactId>
+1
View File
@@ -48,4 +48,5 @@
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>
+3 -3
View File
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<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>jersey</artifactId>
<version>0.0.1-SNAPSHOT</version>
+1
View File
@@ -7,3 +7,4 @@ This module contains articles about JSON.
- [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter)
- [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi)
- [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data)
- [Generate a Java Class From JSON](https://www.baeldung.com/java-generate-class-from-json)
@@ -17,7 +17,22 @@ import com.sun.codemodel.JCodeModel;
public class JsonToJavaClassConversion {
public Object convertJsonToJavaClass(URL inputJson, File outputJavaClassDirectory, String packageName, String className) throws IOException {
public static void main(String[] args) {
String packageName = "com.baeldung.jsontojavaclass.pojo";
String basePath = "src/main/resources";
File inputJson = new File(basePath + File.separator + "input.json");
File outputPojoDirectory = new File(basePath + File.separator + "convertedPojo");
outputPojoDirectory.mkdirs();
try {
new JsonToJavaClassConversion().convertJsonToJavaClass(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
System.out.println("Encountered issue while converting to pojo: " + e.getMessage());
e.printStackTrace();
}
}
public void convertJsonToJavaClass(URL inputJsonUrl, File outputJavaClassDirectory, String packageName, String javaClassName) throws IOException {
JCodeModel jcodeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
@@ -33,10 +48,9 @@ public class JsonToJavaClassConversion {
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(jcodeModel, className, packageName, inputJson);
mapper.generate(jcodeModel, javaClassName, packageName, inputJsonUrl);
jcodeModel.build(outputJavaClassDirectory);
return mapper;
}
}
@@ -5,9 +5,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -16,7 +14,14 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "name", "area", "author", "id", "salary", "topics" })
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"salary",
"topics"
})
@Generated("jsonschema2pojo")
public class SamplePojo {
@@ -143,40 +148,37 @@ public class SamplePojo {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SamplePojo.class.getName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(this)))
.append('[');
sb.append(SamplePojo.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null) ? "<null>" : this.name));
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null) ? "<null>" : this.area));
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null) ? "<null>" : this.author));
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null) ? "<null>" : this.id));
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("salary");
sb.append('=');
sb.append(((this.salary == null) ? "<null>" : this.salary));
sb.append(((this.salary == null)?"<null>":this.salary));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null) ? "<null>" : this.topics));
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null) ? "<null>" : this.additionalProperties));
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length() - 1)) == ',') {
sb.setCharAt((sb.length() - 1), ']');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
@@ -186,13 +188,13 @@ public class SamplePojo {
@Override
public int hashCode() {
int result = 1;
result = ((result * 31) + ((this.area == null) ? 0 : this.area.hashCode()));
result = ((result * 31) + ((this.author == null) ? 0 : this.author.hashCode()));
result = ((result * 31) + ((this.topics == null) ? 0 : this.topics.hashCode()));
result = ((result * 31) + ((this.name == null) ? 0 : this.name.hashCode()));
result = ((result * 31) + ((this.id == null) ? 0 : this.id.hashCode()));
result = ((result * 31) + ((this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode()));
result = ((result * 31) + ((this.salary == null) ? 0 : this.salary.hashCode()));
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.salary == null)? 0 :this.salary.hashCode()));
return result;
}
@@ -205,10 +207,7 @@ public class SamplePojo {
return false;
}
SamplePojo rhs = ((SamplePojo) other);
return ((((((((this.area == rhs.area) || ((this.area != null) && this.area.equals(rhs.area))) && ((this.author == rhs.author) || ((this.author != null) && this.author.equals(rhs.author))))
&& ((this.topics == rhs.topics) || ((this.topics != null) && this.topics.equals(rhs.topics)))) && ((this.name == rhs.name) || ((this.name != null) && this.name.equals(rhs.name))))
&& ((this.id == rhs.id) || ((this.id != null) && this.id.equals(rhs.id)))) && ((this.additionalProperties == rhs.additionalProperties) || ((this.additionalProperties != null) && this.additionalProperties.equals(rhs.additionalProperties))))
&& ((this.salary == rhs.salary) || ((this.salary != null) && this.salary.equals(rhs.salary))));
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.salary == rhs.salary)||((this.salary!= null)&&this.salary.equals(rhs.salary))));
}
}
@@ -0,0 +1,119 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"city",
"country"
})
@Generated("jsonschema2pojo")
public class Address {
@JsonProperty("city")
private String city;
@JsonProperty("country")
private String country;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("city")
public String getCity() {
return city;
}
@JsonProperty("city")
public void setCity(String city) {
this.city = city;
}
public Address withCity(String city) {
this.city = city;
return this;
}
@JsonProperty("country")
public String getCountry() {
return country;
}
@JsonProperty("country")
public void setCountry(String country) {
this.country = country;
}
public Address withCountry(String country) {
this.country = country;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Address withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Address.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("city");
sb.append('=');
sb.append(((this.city == null)?"<null>":this.city));
sb.append(',');
sb.append("country");
sb.append('=');
sb.append(((this.country == null)?"<null>":this.country));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.country == null)? 0 :this.country.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.city == null)? 0 :this.city.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Address) == false) {
return false;
}
Address rhs = ((Address) other);
return ((((this.country == rhs.country)||((this.country!= null)&&this.country.equals(rhs.country)))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.city == rhs.city)||((this.city!= null)&&this.city.equals(rhs.city))));
}
}
@@ -0,0 +1,213 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"topics",
"address"
})
@Generated("jsonschema2pojo")
public class Input {
@JsonProperty("name")
private String name;
@JsonProperty("area")
private String area;
@JsonProperty("author")
private String author;
@JsonProperty("id")
private Integer id;
@JsonProperty("topics")
private List<String> topics = new ArrayList<String>();
@JsonProperty("address")
private Address address;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public Input withName(String name) {
this.name = name;
return this;
}
@JsonProperty("area")
public String getArea() {
return area;
}
@JsonProperty("area")
public void setArea(String area) {
this.area = area;
}
public Input withArea(String area) {
this.area = area;
return this;
}
@JsonProperty("author")
public String getAuthor() {
return author;
}
@JsonProperty("author")
public void setAuthor(String author) {
this.author = author;
}
public Input withAuthor(String author) {
this.author = author;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public Input withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("topics")
public List<String> getTopics() {
return topics;
}
@JsonProperty("topics")
public void setTopics(List<String> topics) {
this.topics = topics;
}
public Input withTopics(List<String> topics) {
this.topics = topics;
return this;
}
@JsonProperty("address")
public Address getAddress() {
return address;
}
@JsonProperty("address")
public void setAddress(Address address) {
this.address = address;
}
public Input withAddress(Address address) {
this.address = address;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Input withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Input.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("address");
sb.append('=');
sb.append(((this.address == null)?"<null>":this.address));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.address == null)? 0 :this.address.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Input) == false) {
return false;
}
Input rhs = ((Input) other);
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.address == rhs.address)||((this.address!= null)&&this.address.equals(rhs.address))))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))));
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "Baeldung",
"area": "tech blogs",
"author": "Eugen",
"id": 32134,
"topics": [
"java",
"kotlin",
"cs",
"linux"
],
"address": {
"city": "Bucharest",
"country": "Romania"
}
}
@@ -3,6 +3,7 @@ package com.baeldung.jsontojavaclass;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -21,17 +22,16 @@ class JsonToJavaClassConversionUnitTest {
File inputJson = new File(jsonPath + "sample_input.json");
// create the local directory for generating the Java Class file
String outputPath = "src/main/java/";
String outputPath = "src/test/resources/";
File outputJavaClassDirectory = new File(outputPath);
outputJavaClassDirectory.mkdirs();
String className = "SamplePojo";
String javaClassName = "SamplePojo";
Object object = jsonToJavaConversion.convertJsonToJavaClass(inputJson.toURI()
.toURL(), outputJavaClassDirectory, packageName, className);
System.out.println(object);
jsonToJavaConversion.convertJsonToJavaClass(inputJson.toURI()
.toURL(), outputJavaClassDirectory, packageName, javaClassName);
Assertions.assertNotNull(object);
File outputJavaClassPath = new File(outputPath + packageName.replace(".", "/"));
Assertions.assertTrue(Arrays.stream(outputJavaClassPath.listFiles()).peek(System.out::println).anyMatch(file -> (javaClassName+".java").equalsIgnoreCase(file.getName())));
}
@@ -0,0 +1,213 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"salary",
"topics"
})
@Generated("jsonschema2pojo")
public class SamplePojo {
@JsonProperty("name")
private String name;
@JsonProperty("area")
private String area;
@JsonProperty("author")
private String author;
@JsonProperty("id")
private Integer id;
@JsonProperty("salary")
private Integer salary;
@JsonProperty("topics")
private List<String> topics = new ArrayList<String>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public SamplePojo withName(String name) {
this.name = name;
return this;
}
@JsonProperty("area")
public String getArea() {
return area;
}
@JsonProperty("area")
public void setArea(String area) {
this.area = area;
}
public SamplePojo withArea(String area) {
this.area = area;
return this;
}
@JsonProperty("author")
public String getAuthor() {
return author;
}
@JsonProperty("author")
public void setAuthor(String author) {
this.author = author;
}
public SamplePojo withAuthor(String author) {
this.author = author;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public SamplePojo withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("salary")
public Integer getSalary() {
return salary;
}
@JsonProperty("salary")
public void setSalary(Integer salary) {
this.salary = salary;
}
public SamplePojo withSalary(Integer salary) {
this.salary = salary;
return this;
}
@JsonProperty("topics")
public List<String> getTopics() {
return topics;
}
@JsonProperty("topics")
public void setTopics(List<String> topics) {
this.topics = topics;
}
public SamplePojo withTopics(List<String> topics) {
this.topics = topics;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public SamplePojo withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SamplePojo.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("salary");
sb.append('=');
sb.append(((this.salary == null)?"<null>":this.salary));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.salary == null)? 0 :this.salary.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof SamplePojo) == false) {
return false;
}
SamplePojo rhs = ((SamplePojo) other);
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.salary == rhs.salary)||((this.salary!= null)&&this.salary.equals(rhs.salary))));
}
}
-1
View File
@@ -29,7 +29,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
+1 -6
View File
@@ -28,34 +28,29 @@
<artifactId>ksqldb-api-client</artifactId>
<version>${ksqldb.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -71,4 +66,4 @@
<testcontainers.version>1.15.3</testcontainers.version>
</properties>
</project>
</project>
@@ -1,3 +1,4 @@
## Relevant Articles:
- [Creating a Kubertes Admission Controller in Java](https://www.baeldung.com/java-kubernetes-admission-controller)
- [Access Control Models](https://www.baeldung.com/java-access-control-models)
-1
View File
@@ -17,7 +17,6 @@
<artifactId>client-java</artifactId>
<version>11.0.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
+2 -3
View File
@@ -104,12 +104,12 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.univocity</groupId>
@@ -161,7 +161,6 @@
<suanshu.version>4.0.0</suanshu.version>
<derive4j.version>1.1.0</derive4j.version>
<assertj.version>3.6.2</assertj.version>
<slf4j.version>1.7.25</slf4j.version>
<awaitility.version>3.0.0</awaitility.version>
<univocity.version>2.8.4</univocity.version>
<guava.version>29.0-jre</guava.version>
+1 -2
View File
@@ -108,7 +108,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.storm</groupId>
@@ -173,7 +173,6 @@
<hazelcast.version>3.8.4</hazelcast.version>
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
<slf4j.version>1.7.25</slf4j.version>
<jmapper.version>1.6.0.1</jmapper.version>
</properties>
@@ -1,22 +1,23 @@
package com.baeldung.java.io.zip4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class CreateSplitZipFile {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
int splitLength = 1024 * 1024 * 10; //10MB
int splitLength = 1024 * 1024 * 10; // 10MB
zipFile.createSplitZipFile(Arrays.asList(new File("aFile.txt")), zipParameters, true, splitLength);
zipFile.createSplitZipFileFromFolder(new File("/users/folder_to_add"), zipParameters, true, splitLength);
zipFile.close();
}
}
@@ -1,12 +1,14 @@
package com.baeldung.java.io.zip4j;
import java.io.IOException;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
public class ExtractAllFile {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.extractAll("/destination_directory");
zipFile.close();
}
}
@@ -1,12 +1,14 @@
package com.baeldung.java.io.zip4j;
import java.io.IOException;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
public class ExtractSingleFile {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.extractFile("aFile.txt", "/destination_directory");
zipFile.close();
}
}
@@ -1,19 +1,20 @@
package com.baeldung.java.io.zip4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import java.io.File;
import java.io.IOException;
public class ZipFolder {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFolder(new File("/users/folder_to_add"), zipParameters);
zipFile.close();
}
}
@@ -1,27 +1,34 @@
package com.baeldung.java.io.zip4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class ZipMultiFile {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
List<File> filesToAdd = Arrays.asList(
new File("aFile.txt"),
new File("bFile.txt")
);
File firstFile = new File("aFile.txt");
File secondFile = new File("bFile.txt");
if (!firstFile.exists()) {
firstFile.createNewFile();
}
if (!secondFile.exists()) {
secondFile.createNewFile();
}
List<File> filesToAdd = Arrays.asList(firstFile, secondFile);
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);
zipFile.close();
}
}
@@ -1,21 +1,27 @@
package com.baeldung.java.io.zip4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import java.io.File;
import java.io.IOException;
public class ZipSingleFile {
public static void main(String[] args) throws ZipException {
public static void main(String[] args) throws IOException {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setCompressionLevel(CompressionLevel.HIGHER);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFile(new File("aFile.txt"));
File fileToAdd = new File("aFile.txt");
if (!fileToAdd.exists()) {
fileToAdd.createNewFile();
}
zipFile.addFile(fileToAdd);
zipFile.close();
}
}
-1
View File
@@ -69,7 +69,6 @@
</dependencies>
<properties>
<logback.version>1.2.3</logback.version>
<logback.contrib.version>0.1.5</logback.contrib.version>
<docx4j.version>3.3.5</docx4j.version>
<javax.mail.version>1.4.7</javax.mail.version>
+3 -3
View File
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<project
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>mapstruct</artifactId>
<version>1.0</version>
@@ -90,4 +90,4 @@
<assertj.version>3.16.1</assertj.version>
</properties>
</project>
</project>
+11 -13
View File
@@ -1,28 +1,17 @@
<?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">
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.maven.plugin</groupId>
<artifactId>host-maven-repo-example</artifactId>
<version>1.0-SNAPSHOT</version>
<url>https://github.com/sgrverma23/host-maven-repo-example.git</url>
<properties>
<github.global.server>github</github.global.server>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<scm>
<url>https://github.com/sgrverma23/host-maven-repo-example.git</url>
<connection>scm:git:git@github.com:sgrverma23/host-maven-repo-example.git</connection>
<developerConnection>scm:git:git@github.com:sgrverma23/host-maven-repo-example.git</developerConnection>
</scm>
<distributionManagement>
<repository>
<id>internal.repo</id>
@@ -30,6 +19,7 @@
<url>file://${project.build.directory}/mvn-artifact</url>
</repository>
</distributionManagement>
<build>
<plugins>
<plugin>
@@ -95,6 +85,7 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>PROJECT-REPO-URL</id>
@@ -105,4 +96,11 @@
</snapshots>
</repository>
</repositories>
<properties>
<github.global.server>github</github.global.server>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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</groupId>
<artifactId>maven-dependency</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<artifactId>maven-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,11 @@
package com.baeldung;
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
StringUtils.isBlank(" ");
}
}
@@ -1,3 +1,3 @@
### Relevant Articles:
- [Understanding the "relativePath" Tag - Maven Parent POM Resolution At A Glance](https://www.baeldung.com/maven-relativepath)
- [Understanding Mavens “relativePath Tag for a Parent POM](https://www.baeldung.com/maven-relativepath)
@@ -4,12 +4,13 @@
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>module1</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>
<packaging>pom</packaging>
</project>
@@ -4,6 +4,8 @@
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>module3</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
@@ -12,6 +14,5 @@
<!-- it only works in IntelliJ IDEA when project-a is registered as a Maven Project -->
<relativePath>../../pom.xml</relativePath>
</parent>
<packaging>pom</packaging>
</project>
@@ -4,6 +4,8 @@
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>module2</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>module1</artifactId>
@@ -11,7 +13,6 @@
<relativePath>../module1/pom.xml</relativePath>
<!-- The parent pom is resolved to project a's pom.xml -->
</parent>
<packaging>pom</packaging>
<modules>
<module>module3</module>
@@ -5,13 +5,14 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven-parent-pom-resolution</groupId>
<artifactId>aggregator</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-parent-pom-resolution</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- The parent pom is resolved to ../pom.xml -->
</parent>
<packaging>pom</packaging>
<modules>
<module>module1</module>
@@ -25,4 +25,4 @@
</pluginManagement>
</build>
</project>
</project>
+3 -2
View File
@@ -53,7 +53,8 @@
<message>
Hello, world
Embed a line break: ${line.separator}
ArtifactId is ${project.artifactId}
ArtifactId is
${project.artifactId}
</message>
<level>INFO</level>
<toFile>/logs/log-echo.txt</toFile>
@@ -76,7 +77,7 @@
<source>
log.info('Test message: {}', 'Hello, World!')
log.info('Embed a line break {}', System.lineSeparator())
log.info('ArtifactId is: ${project.artifactId}')
log.info('ArtifactId is: ${project.artifactId}')
log.warn('Message only in debug mode')
</source>
</configuration>
+4 -4
View File
@@ -13,12 +13,12 @@
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<version>${junit.version}</version>
</dependency>
</dependencies>
@@ -46,7 +46,7 @@
<properties>
<name>${project.name}</name>
<my.awesome.property>property-from-pom</my.awesome.property>
<junit.version>4.13</junit.version>
<junit.version>4.13</junit.version>
</properties>
</project>
</project>
+1 -1
View File
@@ -7,11 +7,11 @@
<version>0.0.1-SNAPSHOT</version>
<name>maven-surefire-plugin</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>
+2 -1
View File
@@ -37,6 +37,7 @@
<module>plugin-management</module>
<module>maven-surefire-plugin</module>
<module>maven-parent-pom-resolution</module>
<module>maven-dependency-management</module>
</modules>
</project>
</project>
+1 -2
View File
@@ -61,7 +61,7 @@
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${lombok.version}</version>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
@@ -145,7 +145,6 @@
<micronaut.version>1.0.0.RC2</micronaut.version>
<jdk.version>1.8</jdk.version>
<annotation.api.version>1.3.2</annotation.api.version>
<lombok.version>1.2.3</lombok.version>
<reactor.version>3.1.6.RELEASE</reactor.version>
<compiler.plugin.version>3.7.0</compiler.plugin.version>
<shade.plugin.version>3.1.0</shade.plugin.version>
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
<project 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"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<artifactId>oauth2-authorization-server</artifactId>
<name>oauth2-authorization-server</name>
+2 -2
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
<project 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"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<artifactId>oauth2-client</artifactId>
<name>oauth2-client</name>
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
<project 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"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<artifactId>oauth2-resource-server</artifactId>
<name>oauth2-resource-server</name>
+2 -2
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
<project 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"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.oauth2</groupId>
<artifactId>oauth2-framework-impl</artifactId>
-2
View File
@@ -37,9 +37,7 @@
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${project.version}</Bundle-Version>
<Bundle-Activator>com.baeldung.osgi.sample.client.Client</Bundle-Activator>
<Private-Package>com.baeldung.osgi.sample.client</Private-Package>
</instructions>
</configuration>
</plugin>
+1 -1
View File
@@ -81,7 +81,7 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.5.1</spring-boot.version>
<spring-boot.version>2.5.4</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
<!-- this property can be removed once we update Mockito version in the main pom.xml -->
<mockito.version>3.4.0</mockito.version>
@@ -55,7 +55,6 @@
<mysql-connector.version>6.0.6</mysql-connector.version>
<spring-boot.version>2.5.3</spring-boot.version>
<rest-assured.version>3.3.0</rest-assured.version>
</properties>
</project>
-1
View File
@@ -8,5 +8,4 @@
<version>1.0.0-SNAPSHOT</version>
<name>design-patterns-cloud</name>
<packaging>pom</packaging>
</project>
+27 -26
View File
@@ -1,31 +1,32 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>simple-hexagonal-example</artifactId>
<name>simpleHexagonalExample</name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>simple-hexagonal-example</artifactId>
<name>simpleHexagonalExample</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<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-web</artifactId>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+24
View File
@@ -71,6 +71,26 @@
<artifactId>flying-saucer-pdf</artifactId>
<version>${flying-saucer-pdf.version}</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-openpdf</artifactId>
<version>${flying-saucer-pdf-openpdf.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-core</artifactId>
<version>${open-html-pdf-core.version}</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>${open-html-pdfbox.version}</version>
</dependency>
</dependencies>
<build>
@@ -93,6 +113,10 @@
<poi-ooxml.version>3.15</poi-ooxml.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<flying-saucer-pdf.version>9.1.20</flying-saucer-pdf.version>
<open-html-pdfbox.version>1.0.6</open-html-pdfbox.version>
<open-html-pdf-core.version>1.0.6</open-html-pdf-core.version>
<flying-saucer-pdf-openpdf.version>9.1.22</flying-saucer-pdf-openpdf.version>
<jsoup.version>1.14.2</jsoup.version>
</properties>
</project>
@@ -0,0 +1,56 @@
package com.baeldung.pdf.openpdf;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;
import com.lowagie.text.Image;
public class CustomElementFactoryImpl implements ReplacedElementFactory {
@Override
public ReplacedElement createReplacedElement(LayoutContext lc, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
Element e = box.getElement();
String nodeName = e.getNodeName();
if (nodeName.equals("img")) {
String imagePath = e.getAttribute("src");
try {
InputStream input = new FileInputStream("src/main/resources/" + imagePath);
byte[] bytes = IOUtils.toByteArray(input);
Image image = Image.getInstance(bytes);
FSImage fsImage = new ITextFSImage(image);
if (cssWidth != -1 || cssHeight != -1) {
fsImage.scale(cssWidth, cssHeight);
} else {
fsImage.scale(2000, 1000);
}
return new ITextImageElement(fsImage);
} catch (Exception e1) {
e1.printStackTrace();
}
}
return null;
}
@Override
public void reset() {
}
@Override
public void remove(Element e) {
}
@Override
public void setFormSubmissionListener(FormSubmissionListener listener) {
}
}
@@ -0,0 +1,53 @@
package com.baeldung.pdf.openpdf;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Html2PdfUsingFlyingSaucer {
private static final String HTML_INPUT = "src/main/resources/htmlforopenpdf.html";
private static final String PDF_OUTPUT = "src/main/resources/html2pdf.pdf";
public static void main(String[] args) {
try {
Html2PdfUsingFlyingSaucer htmlToPdf = new Html2PdfUsingFlyingSaucer();
htmlToPdf.generateHtmlToPdf();
} catch (Exception e) {
e.printStackTrace();
}
}
private void generateHtmlToPdf() throws Exception {
File inputHTML = new File(HTML_INPUT);
Document inputHtml = createWellFormedHtml(inputHTML);
File outputPdf = new File(PDF_OUTPUT);
xhtmlToPdf(inputHtml, outputPdf);
}
private Document createWellFormedHtml(File inputHTML) throws IOException {
Document document = Jsoup.parse(inputHTML, "UTF-8");
document.outputSettings()
.syntax(Document.OutputSettings.Syntax.xml);
return document;
}
private void xhtmlToPdf(Document xhtml, File outputPdf) throws Exception {
try (OutputStream outputStream = new FileOutputStream(outputPdf)) {
ITextRenderer renderer = new ITextRenderer();
SharedContext sharedContext = renderer.getSharedContext();
sharedContext.setPrint(true);
sharedContext.setInteractive(false);
sharedContext.setReplacedElementFactory(new CustomElementFactoryImpl());
renderer.setDocumentFromString(xhtml.html());
renderer.layout();
renderer.createPDF(outputStream);
}
}
}
@@ -0,0 +1,55 @@
package com.baeldung.pdf.openpdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.jsoup.nodes.Document;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
public class Html2PdfUsingOpenHtml {
private static final String HTML_INPUT = "src/main/resources/htmlforopenpdf.html";
private static final String PDF_OUTPUT = "src/main/resources/html2pdf.pdf";
public static void main(String[] args) {
try {
Html2PdfUsingOpenHtml htmlToPdf = new Html2PdfUsingOpenHtml();
htmlToPdf.generateHtmlToPdf();
} catch (Exception e) {
e.printStackTrace();
}
}
private void generateHtmlToPdf() throws IOException {
File inputHTML = new File(HTML_INPUT);
Document doc = createWellFormedHtml(inputHTML);
xhtmlToPdf(doc, PDF_OUTPUT);
}
private Document createWellFormedHtml(File inputHTML) throws IOException {
Document document = Jsoup.parse(inputHTML, "UTF-8");
document.outputSettings()
.syntax(Document.OutputSettings.Syntax.xml);
return document;
}
private void xhtmlToPdf(Document doc, String outputPdf) throws IOException {
try (OutputStream os = new FileOutputStream(outputPdf)) {
String baseUri = FileSystems.getDefault()
.getPath("src/main/resources/")
.toUri()
.toString();
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withUri(outputPdf);
builder.toStream(os);
builder.withW3cDocument(new W3CDom().fromJsoup(doc), baseUri);
builder.run();
}
}
}
Binary file not shown.
@@ -0,0 +1,26 @@
<html>
<head>
<style>
.center_div {
border: 1px solid gray;
margin-left: auto;
margin-right: auto;
width: 90%;
background-color: #d0f0f6;
text-align: left;
padding: 8px;
}
</style>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="center_div">
<h1>Hello Baeldung!</h1>
<img src="Java_logo.png">
<div class="myclass">
<p>This is the tutorial to convert html to pdf.</p>
</div>
</div>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
.myclass{
font-family: Helvetica, sans-serif;
font-size:25;
font-weight: normal;
color: blue;
}
+32 -32
View File
@@ -16,6 +16,38 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM).
A BOM specifies the versions of a "stack" (or a collection) of artifacts. We use this here so that we
always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you
can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such
as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss
stack of the Java EE 7 APIs, with extras from the Hibernate family of projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.distribution</groupId>
<artifactId>distributions-bom</artifactId>
<version>${deltaspike.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- First declare the APIs we depend on and need for compilation. All of them are provided by
JBoss WildFly -->
@@ -245,38 +277,6 @@
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM).
A BOM specifies the versions of a "stack" (or a collection) of artifacts. We use this here so that we
always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you
can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such
as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss
stack of the Java EE 7 APIs, with extras from the Hibernate family of projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${jboss.bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.distribution</groupId>
<artifactId>distributions-bom</artifactId>
<version>${deltaspike.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<querydsl.version>3.7.4</querydsl.version>
<deltaspike.version>1.8.2</deltaspike.version>

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