Merge pull request #58 from eugenp/master

update
This commit is contained in:
Maiklins 2020-06-15 18:26:03 +02:00 committed by GitHub
commit d329bf73b8
87 changed files with 1353 additions and 135 deletions

View File

@ -5,21 +5,21 @@ import static com.baeldung.algorithms.quicksort.SortingUtils.swap;
public class DutchNationalFlagPartioning { public class DutchNationalFlagPartioning {
public static Partition partition(int[] a, int begin, int end) { public static Partition partition(int[] input, int begin, int end) {
int lt = begin, current = begin, gt = end; int lt = begin, current = begin, gt = end;
int partitioningValue = a[begin]; int partitioningValue = input[begin];
while (current <= gt) { while (current <= gt) {
int compareCurrent = compare(a[current], partitioningValue); int compareCurrent = compare(input[current], partitioningValue);
switch (compareCurrent) { switch (compareCurrent) {
case -1: case -1:
swap(a, current++, lt++); swap(input, current++, lt++);
break; break;
case 0: case 0:
current++; current++;
break; break;
case 1: case 1:
swap(a, current, gt--); swap(input, current, gt--);
break; break;
} }
} }

View File

@ -9,3 +9,4 @@ This module contains articles about Java 14.
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) - [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) - [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access) - [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)

View File

@ -5,7 +5,7 @@ This module contains articles about the improvements to core Java features intro
### Relevant Articles: ### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods) - [Java Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) - [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new) - [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture) - [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)

View File

@ -13,4 +13,5 @@ This module contains articles about advanced topics about multithreading with co
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) - [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference) - [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency) - [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -13,3 +13,4 @@ This module contains articles about concurrent Java collections
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) - [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) - [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) - [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)

View File

@ -0,0 +1,82 @@
package com.baeldung.exceptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
public class TooManyOpenFilesExceptionLiveTest {
private File tempFile;
@BeforeEach
public void setUp() throws IOException {
tempFile = File.createTempFile("testForException", "tmp");
}
@AfterEach
public void tearDown() {
System.gc();
tempFile.delete();
}
@Test
public void whenNotClosingResoures_thenIOExceptionShouldBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream leakyHandle = new FileInputStream(tempFile);
}
Assertions.fail("Method Should Have Failed");
} catch (IOException e) {
assertTrue(e.getMessage().toLowerCase().contains("too many open files"));
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenClosingResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
FileInputStream nonLeakyHandle = null;
try {
nonLeakyHandle = new FileInputStream(tempFile);
} finally {
if (nonLeakyHandle != null) {
nonLeakyHandle.close();
}
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
@Test
public void whenUsingTryWithResoures_thenIOExceptionShouldNotBeThrown() {
try {
for (int x = 0; x < 1000000; x++) {
try (FileInputStream nonLeakyHandle = new FileInputStream(tempFile)) {
//Do something with the file
}
}
} catch (IOException e) {
assertFalse(e.getMessage().toLowerCase().contains("too many open files"));
Assertions.fail("Method Should Not Have Failed");
} catch (Exception e) {
Assertions.fail("Unexpected exception");
}
}
}

View File

@ -51,14 +51,31 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath> <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>${asm.version}</version>
</dependency>
<dependency>
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>${bcel.version}</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<!-- instrumentation --> <!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version> <javaassist.version>3.27.0-GA</javaassist.version>
<esapi.version>2.1.0.1</esapi.version> <esapi.version>2.1.0.1</esapi.version>
<sun.tools.version>1.8.0</sun.tools.version> <sun.tools.version>1.8.0</sun.tools.version>
<asm.version>8.0.1</asm.version>
<bcel.version>6.5.0</bcel.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,51 @@
package com.baeldung.bytecode;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.JavaClass;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.util.TraceClassVisitor;
import javassist.ClassPool;
import javassist.NotFoundException;
import javassist.bytecode.ClassFile;
public class ViewBytecodeUnitTest {
@Test
public void whenUsingASM_thenReadBytecode() throws IOException {
ClassReader reader = new ClassReader("java.lang.Object");
StringWriter sw = new StringWriter();
TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(sw));
reader.accept(tcv, 0);
assertTrue(sw.toString().contains("public class java/lang/Object"));
}
@Test
public void whenUsingBCEL_thenReadBytecode() throws ClassNotFoundException {
JavaClass objectClazz = Repository.lookupClass("java.lang.Object");
assertEquals(objectClazz.getClassName(), "java.lang.Object");
assertEquals(objectClazz.getMethods().length, 14);
assertTrue(objectClazz.toString().contains("public class java.lang.Object"));
}
@Test
public void whenUsingJavassist_thenReadBytecode() throws NotFoundException {
ClassPool cp = ClassPool.getDefault();
ClassFile cf = cp.get("java.lang.Object").getClassFile();
assertEquals(cf.getName(), "java.lang.Object");
assertEquals(cf.getMethods().size(), 14);
}
}

View File

@ -6,7 +6,6 @@
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math) - [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic) - [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) - [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator) - [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow) - [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
- [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set) - [Obtaining a Power Set of a Set in Java](https://www.baeldung.com/java-power-set-of-a-set)

View File

@ -12,3 +12,4 @@ This module contains articles about Java operators
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator) - [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and) - [Bitwise & vs Logical && Operators](https://www.baeldung.com/java-bitwise-vs-logical-and)
- [Finding an Objects Class in Java](https://www.baeldung.com/java-finding-class)

View File

@ -17,6 +17,15 @@ public class StringToIntOrIntegerUnitTest {
assertThat(result).isEqualTo(42); assertThat(result).isEqualTo(42);
} }
@Test
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
String givenString = "101010";
int result = Integer.parseInt(givenString, 2);
assertThat(result).isEqualTo(42);
}
@Test @Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "42"; String givenString = "42";
@ -26,6 +35,15 @@ public class StringToIntOrIntegerUnitTest {
assertThat(result).isEqualTo(new Integer(42)); assertThat(result).isEqualTo(new Integer(42));
} }
@Test
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
String givenString = "101010";
Integer result = Integer.valueOf(givenString, 2);
assertThat(result).isEqualTo(new Integer(42));
}
@Test @Test
public void givenString_whenCallingValueOf_shouldCacheSomeValues() { public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
for (int i = -128; i <= 127; i++) { for (int i = -128; i <= 127; i++) {

View File

@ -11,4 +11,5 @@ This module contains articles about core features in the Kotlin language.
- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization) - [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization)
- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety) - [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety)
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) - [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
- [Checking Whether a lateinit var Is Initialized in Kotlin](https://www.baeldung.com/kotlin/checking-lateinit)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang) - [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang)

View File

@ -5,5 +5,4 @@ This module contains articles about Drools
### Relevant Articles: ### Relevant Articles:
- [Introduction to Drools](https://www.baeldung.com/drools) - [Introduction to Drools](https://www.baeldung.com/drools)
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining) - [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)

View File

@ -16,12 +16,39 @@
<build> <build>
<finalName>guava-collections-map</finalName> <finalName>guava-collections-map</finalName>
<resources> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
<filtering>true</filtering> <filtering>true</filtering>
</resource> </resource>
</resources> </resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build> </build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project> </project>

View File

@ -13,8 +13,32 @@
<relativePath>../parent-java</relativePath> <relativePath>../parent-java</relativePath>
</parent> </parent>
<build>
<finalName>guava-collections-set</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@ -23,13 +47,10 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<finalName>guava-collections-set</finalName>
</build>
<properties> <properties>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties> </properties>
</project> </project>

View File

@ -15,6 +15,25 @@
<relativePath>../parent-java</relativePath> <relativePath>../parent-java</relativePath>
</parent> </parent>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<!-- utils --> <!-- utils -->
<dependency> <dependency>
@ -27,7 +46,20 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@ -44,16 +76,6 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties> <properties>
<!-- util --> <!-- util -->
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
@ -61,6 +83,7 @@
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version> <java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties> </properties>
</project> </project>

View File

@ -4,6 +4,9 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>guava-io</artifactId> <artifactId>guava-io</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
<name>guava-io</name> <name>guava-io</name>
<parent> <parent>
@ -15,12 +18,35 @@
<build> <build>
<finalName>guava-io</finalName> <finalName>guava-io</finalName>
<resources> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
<filtering>true</filtering> <filtering>true</filtering>
</resource> </resource>
</resources> </resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build> </build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -11,8 +11,11 @@ import java.io.FileOutputStream;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
@ -31,6 +34,21 @@ import com.google.common.io.Resources;
public class GuavaIOUnitTest { public class GuavaIOUnitTest {
@After
public void afterEach() throws Exception {
deleteProducedFiles();
}
private void deleteProducedFiles() throws IOException {
deleteIfExists("test.out");
deleteIfExists("test_copy.in");
deleteIfExists("test_le.txt");
}
private void deleteIfExists(String fileName) throws IOException {
java.nio.file.Files.deleteIfExists(Paths.get("src", "test", "resources", fileName));
}
@Test @Test
public void whenWriteUsingFiles_thenWritten() throws IOException { public void whenWriteUsingFiles_thenWritten() throws IOException {
final String expectedValue = "Hello world"; final String expectedValue = "Hello world";
@ -206,5 +224,4 @@ public class GuavaIOUnitTest {
assertEquals(value, result); assertEquals(value, result);
} }
} }

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Test

View File

@ -0,0 +1,4 @@
John
Jane
Adam
Tom

View File

@ -8,9 +8,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<properties> <properties>

View File

@ -8,9 +8,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<properties> <properties>

View File

@ -8,9 +8,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -4,13 +4,16 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>guava-modules</artifactId> <artifactId>guava-modules</artifactId>
<name>guava-modules</name> <name>guava-modules</name>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-java</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>..</relativePath> <relativePath>../parent-java</relativePath>
</parent> </parent>
<modules> <modules>
@ -19,4 +22,28 @@
<module>guava-21</module> <module>guava-21</module>
</modules> </modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -15,13 +15,45 @@
<relativePath>../parent-java</relativePath> <relativePath>../parent-java</relativePath>
</parent> </parent>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@ -30,18 +62,9 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties> <properties>
<!-- testing --> <!-- testing -->
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
</properties> </properties>

View File

@ -23,6 +23,16 @@
<module>jackson-exceptions</module> <module>jackson-exceptions</module>
</modules> </modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
@ -35,6 +45,22 @@
<artifactId>jackson-dataformat-xml</artifactId> <artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project> </project>

View File

@ -13,6 +13,25 @@
<relativePath>../parent-java</relativePath> <relativePath>../parent-java</relativePath>
</parent> </parent>
<build>
<finalName>jackson-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<!--jackson for xml --> <!--jackson for xml -->
<dependency> <dependency>
@ -20,7 +39,20 @@
<artifactId>jackson-dataformat-xml</artifactId> <artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version> <version>${jackson.version}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@ -29,18 +61,9 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<finalName>jackson-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties> <properties>
<!-- testing --> <!-- testing -->
<junit-jupiter.version>5.6.2</junit-jupiter.version>
<assertj.version>3.11.0</assertj.version> <assertj.version>3.11.0</assertj.version>
</properties> </properties>

View File

@ -16,5 +16,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Introduction to Takes](https://www.baeldung.com/java-takes) - [Introduction to Takes](https://www.baeldung.com/java-takes)
- [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway)
- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro)
- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker)
- More articles [[<-- prev]](/libraries-2) [[next -->]](/libraries-4) - More articles [[<-- prev]](/libraries-2) [[next -->]](/libraries-4)

View File

@ -12,6 +12,7 @@ This module contains articles about libraries for data processing in Java.
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
- [Intro to Derive4J](https://www.baeldung.com/derive4j) - [Intro to Derive4J](https://www.baeldung.com/derive4j)
- [Java-R Integration](https://www.baeldung.com/java-r-integration) - [Java-R Integration](https://www.baeldung.com/java-r-integration)
- [Univocity Parsers](https://www.baeldung.com/java-univocity-parsers)
- More articles: [[<-- prev]](/../libraries-data) - More articles: [[<-- prev]](/../libraries-data)
##### Building the project ##### Building the project

View File

@ -6,3 +6,4 @@
- [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender) - [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender)
- [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output) - [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output)
- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers) - [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers)
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)

View File

@ -1,3 +0,0 @@
### Relevant Articles:
- [Introduction to Netflix Genie](https://www.baeldung.com/netflix-genie-intro)

View File

@ -2,4 +2,4 @@
- [A Solid Guide to Solid Principles](https://www.baeldung.com/solid-principles) - [A Solid Guide to Solid Principles](https://www.baeldung.com/solid-principles)
- [Single Responsibility Principle in Java](https://www.baeldung.com/java-single-responsibility-principle) - [Single Responsibility Principle in Java](https://www.baeldung.com/java-single-responsibility-principle)
- [Open/Closed Principle in Java](https://www.baeldung.com/java-open-closed-principle)

View File

@ -5,3 +5,4 @@ This module contains articles about PDF files.
### Relevant Articles: ### Relevant Articles:
- [PDF Conversions in Java](https://www.baeldung.com/pdf-conversions-java) - [PDF Conversions in Java](https://www.baeldung.com/pdf-conversions-java)
- [Creating PDF Files in Java](https://www.baeldung.com/java-pdf-creation) - [Creating PDF Files in Java](https://www.baeldung.com/java-pdf-creation)
- [Generating PDF Files Using Thymeleaf](https://www.baeldung.com/thymeleaf-generate-pdf)

View File

@ -60,6 +60,7 @@
</dependencies> </dependencies>
<properties> <properties>
<h2.version>1.4.200</h2.version>
<postgresql.version>42.2.5.jre7</postgresql.version> <postgresql.version>42.2.5.jre7</postgresql.version>
<assertj-core.version>3.10.0</assertj-core.version> <assertj-core.version>3.10.0</assertj-core.version>
<commons-dbcp2.version>2.4.0</commons-dbcp2.version> <commons-dbcp2.version>2.4.0</commons-dbcp2.version>

View File

@ -0,0 +1,93 @@
package com.baeldung.genkeys;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
public class JdbcInsertIdIntegrationTest {
private static final String QUERY = "insert into persons (name) values (?)";
private static Connection connection;
@BeforeClass
public static void setUp() throws Exception {
connection = DriverManager.getConnection("jdbc:h2:mem:generated-keys", "sa", "");
connection
.createStatement()
.execute("create table persons(id bigint auto_increment, name varchar(255))");
}
@AfterClass
public static void tearDown() throws SQLException {
connection
.createStatement()
.execute("drop table persons");
connection.close();
}
@Test
public void givenInsert_whenUsingAutoGenFlag_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(QUERY, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, "Foo");
int affectedRows = statement.executeUpdate();
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingAutoGenFlagViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (Statement statement = connection.createStatement()) {
String query = "insert into persons (name) values ('Foo')";
int affectedRows = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingReturningCols_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(QUERY, new String[] { "id" })) {
statement.setString(1, "Foo");
int affectedRows = statement.executeUpdate();
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
@Test
public void givenInsert_whenUsingReturningColsViaExecute_thenBeAbleToFetchTheIdAfterward() throws SQLException {
try (Statement statement = connection.createStatement()) {
String query = "insert into persons (name) values ('Foo')";
int affectedRows = statement.executeUpdate(query, new String[] { "id" });
assertThat(affectedRows).isPositive();
try (ResultSet keys = statement.getGeneratedKeys()) {
assertThat(keys.next()).isTrue();
assertThat(keys.getLong(1)).isGreaterThanOrEqualTo(1);
}
}
}
}

View File

@ -13,4 +13,5 @@ This module contains articles about the Java Persistence API (JPA) in Java.
- [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type) - [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type)
- [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables) - [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables)
- [Constructing a JPA Query Between Unrelated Entities](https://www.baeldung.com/jpa-query-unrelated-entities) - [Constructing a JPA Query Between Unrelated Entities](https://www.baeldung.com/jpa-query-unrelated-entities)
- [When Does JPA Set the Primary Key](https://www.baeldung.com/jpa-strategies-when-set-primary-key)
- More articles: [[<-- prev]](/java-jpa) - More articles: [[<-- prev]](/java-jpa)

View File

@ -0,0 +1,36 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "app_admin")
public class Admin {
@Id
@GeneratedValue
private Long id;
@Column(name = "admin_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "article_gen")
@SequenceGenerator(name = "article_gen", sequenceName = "article_seq")
private Long id;
@Column(name = "article_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "id_gen")
@Entity
public class IdGenerator {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "gen_name")
private String gen_name;
@Column(name = "gen_value")
private Long gen_value;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGen_name() {
return gen_name;
}
public void setGen_name(String gen_name) {
this.gen_name = gen_name;
}
public Long getGen_value() {
return gen_value;
}
public void setGen_value(Long gen_value) {
this.gen_value = gen_value;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
@Entity
@Table(name = "task")
public class Task {
@Id
@TableGenerator(name = "id_generator", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_value", pkColumnValue = "task_gen", initialValue = 10000, allocationSize = 10)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "id_generator")
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "app_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -184,4 +184,29 @@
value="false" /> value="false" />
</properties> </properties>
</persistence-unit> </persistence-unit>
<persistence-unit name="jpa-h2-primarykey">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.generateidvalue.Admin</class>
<class>com.baeldung.jpa.generateidvalue.Article</class>
<class>com.baeldung.jpa.generateidvalue.IdGenerator</class>
<class>com.baeldung.jpa.generateidvalue.Task</class>
<class>com.baeldung.jpa.generateidvalue.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.sql-load-script-source"
value="primary_key_generator.sql" />
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.weaving" value="static" />
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.jdbc.allow-native-sql-queries" value="true" />
</properties>
</persistence-unit>
</persistence> </persistence>

View File

@ -0,0 +1,4 @@
CREATE SEQUENCE article_seq MINVALUE 1 START WITH 50 INCREMENT BY 50;
INSERT INTO id_gen (gen_name, gen_val) VALUES ('id_generator', 0);
INSERT INTO id_gen (gen_name, gen_val) VALUES ('task_gen', 10000);

View File

@ -0,0 +1,81 @@
package com.baeldung.jpa.generateidvalue;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* PrimaryKeyGeneratorTest class
*
* @author shiwangzhihe@gmail.com
*/
public class PrimaryKeyUnitTest {
private static EntityManager entityManager;
@BeforeClass
public static void setup() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-primarykey");
entityManager = factory.createEntityManager();
}
@Test
public void givenIdentityStrategy_whenCommitTransction_thenReturnPrimaryKey() {
User user = new User();
user.setName("TestName");
entityManager.getTransaction()
.begin();
entityManager.persist(user);
Assert.assertNull(user.getId());
entityManager.getTransaction()
.commit();
Long expectPrimaryKey = 1L;
Assert.assertEquals(expectPrimaryKey, user.getId());
}
@Test
public void givenTableStrategy_whenPersist_thenReturnPrimaryKey() {
Task task = new Task();
task.setName("Test Task");
entityManager.getTransaction()
.begin();
entityManager.persist(task);
Long expectPrimaryKey = 10000L;
Assert.assertEquals(expectPrimaryKey, task.getId());
entityManager.getTransaction()
.commit();
}
@Test
public void givenSequenceStrategy_whenPersist_thenReturnPrimaryKey() {
Article article = new Article();
article.setName("Test Name");
entityManager.getTransaction()
.begin();
entityManager.persist(article);
Long expectPrimaryKey = 51L;
Assert.assertEquals(expectPrimaryKey, article.getId());
entityManager.getTransaction()
.commit();
}
@Test
public void givenAutoStrategy_whenPersist_thenReturnPrimaryKey() {
Admin admin = new Admin();
admin.setName("Test Name");
entityManager.persist(admin);
Long expectPrimaryKey = 1L;
Assert.assertEquals(expectPrimaryKey, admin.getId());
}
}

View File

@ -6,6 +6,7 @@
- [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java) - [Guide to Elasticsearch in Java](https://www.baeldung.com/elasticsearch-java)
- [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial) - [Geospatial Support in ElasticSearch](https://www.baeldung.com/elasticsearch-geo-spatial)
- [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging) - [A Simple Tagging Implementation with Elasticsearch](https://www.baeldung.com/elasticsearch-tagging)
- [Introduction to Spring Data Elasticsearch test 2](https://www.baeldung.com/spring-data-elasticsearch-test-2)
### Build the Project with Tests Running ### Build the Project with Tests Running
``` ```

View File

@ -10,9 +10,9 @@
- [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database) - [Self-Contained Testing Using an In-Memory Database](https://www.baeldung.com/spring-jpa-test-in-memory-database)
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source) - [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource-2)
### Eclipse Config ### Eclipse Config

View File

@ -2,3 +2,4 @@
- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) - [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing)
- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) - [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list)
- [Transactional Annotations: Spring vs. JTA](https://www.baeldung.com/spring-vs-jta-transactional)

View File

@ -4,4 +4,4 @@ This module contains articles about CI/CD with Spring Boot
## Relevant Articles ## Relevant Articles
- [CI/CD for a Spring Boot Project](https://www.baeldung.com/spring-boot-ci-cd) - [Applying CI/CD With Spring Boot](https://www.baeldung.com/spring-boot-ci-cd)

View File

@ -0,0 +1,7 @@
## Spring Boot MVC
This module contains articles about Spring Web MVC in Spring Boot projects.
### Relevant Articles:
- More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2)

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-mvc-3</artifactId>
<name>spring-boot-mvc-3</name>
<packaging>jar</packaging>
<description>Module For Spring Boot MVC Web</description>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.circularviewpath;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring Boot launcher for an application
*
*/
@SpringBootApplication(scanBasePackages = "com.baeldung.controller.circularviewpath")
public class CircularViewPathApplication {
/**
* Launches a Spring Boot application
*
* @param args null
*/
public static void main(String[] args) {
SpringApplication.run(CircularViewPathApplication.class, args);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.controller.circularviewpath;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class CircularViewPathController {
/**
* A request mapping which may cause circular view path exception
*/
@GetMapping("/path")
public String path() {
return "path";
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>path.html</title>
</head>
<body>
<p>path.html</p>
</body>
</html>

View File

@ -7,4 +7,5 @@ This module contains articles about Properties in Spring Boot.
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) - [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) - [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) - [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)
- [@PropertySource with YAML Files in Spring Boot](https://www.baeldung.com/spring-yaml-propertysource)
- More articles: [[<-- prev]](../spring-boot-properties) - More articles: [[<-- prev]](../spring-boot-properties)

View File

@ -1,13 +0,0 @@
# Logs
logs
*.log
# Git
.git
.cache
# Classes
**/*.class
# Ignore md files
*.md

View File

@ -1,10 +0,0 @@
FROM maven:3.6.0-jdk-11
WORKDIR /code/spring-boot-modules/spring-boot-properties/
COPY ./spring-boot-modules/spring-boot-properties/pom.xml .
COPY ./spring-boot-modules/spring-boot-properties/src ./src
COPY ./parent-boot-2/pom.xml /code/parent-boot-2/pom.xml
COPY ./pom.xml /code/pom.xml
COPY ./custom-pmd-0.0.1.jar /code/custom-pmd-0.0.1.jar
COPY ./baeldung-pmd-rules.xml /code/baeldung-pmd-rules.xml
RUN mvn dependency:resolve
CMD ["mvn", "spring-boot:run"]

View File

@ -11,6 +11,9 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.yaml.YAMLConfig.Idm;
import com.baeldung.yaml.YAMLConfig.Service;
@SpringBootApplication @SpringBootApplication
public class MyApplication implements CommandLineRunner { public class MyApplication implements CommandLineRunner {
@ -26,6 +29,23 @@ public class MyApplication implements CommandLineRunner {
System.out.println("using environment:" + myConfig.getEnvironment()); System.out.println("using environment:" + myConfig.getEnvironment());
System.out.println("name:" + myConfig.getName()); System.out.println("name:" + myConfig.getName());
System.out.println("servers:" + myConfig.getServers()); System.out.println("servers:" + myConfig.getServers());
if ("testing".equalsIgnoreCase(myConfig.getEnvironment())) {
System.out.println("external:" + myConfig.getExternal());
System.out.println("map:" + myConfig.getMap());
Idm idm = myConfig.getComponent().getIdm();
Service service = myConfig.getComponent().getService();
System.out.println("Idm:");
System.out.println(" Url: " + idm.getUrl());
System.out.println(" User: " + idm.getUser());
System.out.println(" Password: " + idm.getPassword());
System.out.println(" Description: " + idm.getDescription());
System.out.println("Service:");
System.out.println(" Url: " + service.getUrl());
System.out.println(" Token: " + service.getToken());
System.out.println(" Description: " + service.getDescription());
}
} }
} }

View File

@ -1,7 +1,10 @@
package com.baeldung.yaml; package com.baeldung.yaml;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -13,6 +16,9 @@ public class YAMLConfig {
private String name; private String name;
private String environment; private String environment;
private List<String> servers = new ArrayList<String>(); private List<String> servers = new ArrayList<String>();
private List<String> external = new ArrayList<String>();
private Map<String, String> map = new HashMap<String, String>();
private Component component = new Component();
public List<String> getServers() { public List<String> getServers() {
return servers; return servers;
@ -38,4 +44,110 @@ public class YAMLConfig {
this.environment = environment; this.environment = environment;
} }
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getExternal() {
return external;
}
public void setExternal(List<String> external) {
this.external = external;
}
public class Component {
private Idm idm = new Idm();
private Service service = new Service();
public Idm getIdm() {
return idm;
}
public void setIdm(Idm idm) {
this.idm = idm;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
public class Idm {
private String url;
private String user;
private String password;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Service {
private String url;
private String token;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
} }

View File

@ -13,6 +13,26 @@ servers:
- www.abc.test.com - www.abc.test.com
- www.xyz.test.com - www.xyz.test.com
external: [www.abc.test.com, www.xyz.test.com]
map:
firstkey: key1
secondkey: key2
component:
idm:
url: myurl
user: user
password: password
description: >
this should be a long
description
service:
url: myurlservice
token: token
description: >
this should be another long
description
--- ---
spring: spring:

View File

@ -11,6 +11,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class) @SpringBootTest(classes = MyApplication.class)
@TestPropertySource(properties = {"spring.profiles.active = test"})
class YAMLIntegrationTest { class YAMLIntegrationTest {
@Autowired @Autowired
@ -20,5 +21,6 @@ class YAMLIntegrationTest {
void whenProfileTest_thenNameTesting() { void whenProfileTest_thenNameTesting() {
assertTrue("testing".equalsIgnoreCase(config.getEnvironment())); assertTrue("testing".equalsIgnoreCase(config.getEnvironment()));
assertTrue("test-YAML".equalsIgnoreCase(config.getName())); assertTrue("test-YAML".equalsIgnoreCase(config.getName()));
assertTrue("myurl".equalsIgnoreCase(config.getComponent().getIdm().getUrl()));
} }
} }

View File

@ -1,3 +1,4 @@
### Relevant Articles: ### Relevant Articles:
- [Documenting a Spring REST API Using OpenAPI 3.0](https://www.baeldung.com/spring-rest-openapi-documentation)
- [Documenting a Spring REST API Using OpenAPI 3.0](https://www.baeldung.com/spring-rest-openapi-documentation)
- [Spring REST Docs vs OpenAPI](https://www.baeldung.com/spring-rest-docs-vs-openapi)

View File

@ -22,16 +22,6 @@
<groupId>org.apache.spark</groupId> <groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.version}</artifactId> <artifactId>spark-core_${scala.version}</artifactId>
<version>${spark.version}</version> <version>${spark.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -13,7 +13,7 @@ import java.util.stream.IntStream;
public class PiApproximation { public class PiApproximation {
public static void main(String[] args) { public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation"); SparkConf conf = new SparkConf().setAppName("BaeldungPIApproximation").setMaster("local[2]");
JavaSparkContext context = new JavaSparkContext(conf); JavaSparkContext context = new JavaSparkContext(conf);
int slices = args.length >= 1 ? Integer.valueOf(args[0]) : 2; int slices = args.length >= 1 ? Integer.valueOf(args[0]) : 2;
int n = (100000L * slices) > Integer.MAX_VALUE ? Integer.MAX_VALUE : 100000 * slices; int n = (100000L * slices) > Integer.MAX_VALUE ? Integer.MAX_VALUE : 100000 * slices;

View File

@ -11,9 +11,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId> <artifactId>spring-cloud-data-flow</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-1</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -21,7 +20,7 @@
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version> <version>Hoxton.SR4</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
@ -31,8 +30,7 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-starter</artifactId> <artifactId>spring-cloud-starter-task</artifactId>
<version>${spring-cloud-task-starter.version}</version>
</dependency> </dependency>
<dependency> <dependency>
@ -48,7 +46,7 @@
</dependencies> </dependencies>
<properties> <properties>
<spring-cloud-task-starter.version>1.0.3.RELEASE</spring-cloud-task-starter.version> <spring-cloud-task-starter.version>2.2.3.RELEASE</spring-cloud-task-starter.version>
</properties> </properties>
</project> </project>

View File

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

View File

@ -9,9 +9,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId> <artifactId>spring-cloud-data-flow-etl</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -63,7 +62,7 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties> </properties>
</project> </project>

View File

@ -9,9 +9,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId> <artifactId>spring-cloud-data-flow-etl</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -55,7 +54,7 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties> </properties>
</project> </project>

View File

@ -10,9 +10,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId> <artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -35,7 +34,7 @@
</dependencies> </dependencies>
<properties> <properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties> </properties>
</project> </project>

View File

@ -2,6 +2,7 @@
<project 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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-cloud-data-flow-stream-processing</artifactId> <artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-data-flow-stream-processing</name> <name>spring-cloud-data-flow-stream-processing</name>
@ -9,9 +10,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>spring-cloud-data-flow</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent> </parent>
<modules> <modules>
@ -22,4 +22,12 @@
<module>log-sink</module> <module>log-sink</module>
</modules> </modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -10,9 +10,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId> <artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -35,7 +34,7 @@
</dependencies> </dependencies>
<properties> <properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties> </properties>
</project> </project>

View File

@ -2,6 +2,7 @@
<project 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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>time-source</artifactId> <artifactId>time-source</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>time-source</name> <name>time-source</name>
@ -10,9 +11,8 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-boot-1</artifactId> <artifactId>spring-cloud-data-flow-stream-processing</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-1</relativePath>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
@ -35,7 +35,7 @@
</dependencies> </dependencies>
<properties> <properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version> <spring-cloud-dependencies.version>Hoxton.SR4</spring-cloud-dependencies.version>
</properties> </properties>
</project> </project>

View File

@ -9,10 +9,10 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>parent-boot-1</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>2.1.13.RELEASE</version>
<relativePath>../../../parent-boot-1</relativePath> <relativePath />
</parent> </parent>
<dependencies> <dependencies>
@ -32,6 +32,11 @@
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId> <artifactId>jstl</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -45,7 +50,7 @@
</build> </build>
<properties> <properties>
<spring-cloud-starter-stream.version>1.3.1.RELEASE</spring-cloud-starter-stream.version> <spring-cloud-starter-stream.version>2.1.2.RELEASE</spring-cloud-starter-stream.version>
</properties> </properties>
</project> </project>

View File

@ -8,7 +8,7 @@ import java.util.concurrent.Executors;
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public final class GlobalEventBus { public final class GlobalEventBus {
public static final String GLOBAL_EVENT_BUS_EXPRESSION = "T(com.baeldung.postprocessor.GlobalEventBus).getEventBus()"; public static final String GLOBAL_EVENT_BUS_EXPRESSION = "T(com.baeldung.beanpostprocessor.GlobalEventBus).getEventBus()";
private static final String IDENTIFIER = "global-event-bus"; private static final String IDENTIFIER = "global-event-bus";

View File

@ -0,0 +1,7 @@
## Spring RestTemplate
This module contains articles about Spring RestTemplate
### Relevant Articles:

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-resttemplate</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-resttemplate-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<!-- Spring Boot Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.resttemplate.logging;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.resttemplate.logging.web.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@PostMapping("/persons")
public List<String> getPersons() {
return Arrays.asList(new String[] { "Lucie", "Jackie", "Danesh", "Tao" });
}
}

View File

@ -0,0 +1,2 @@
server.port=8080
server.servlet.context-path=/spring-rest

View File

@ -0,0 +1,29 @@
package com.baeldung.resttemplate.logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
final static Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
log.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
log.debug("Response body: {}", body);
return response;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.resttemplate.logging;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateLoggingLiveTest {
private static final String baseUrl = "http://localhost:8080/spring-rest";
@Test
public void givenHttpClientConfiguration_whenSendGetForRequestEntity_thenRequestResponseFullLog() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenLoggingInterceptorConfiguration_whenSendGetForRequestEntity_thenRequestResponseCustomLog() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(interceptors);
final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
}

View File

@ -0,0 +1,5 @@
logging.level.org.springframework.web.client.RestTemplate=DEBUG
logging.level.com.baeldung.resttemplate.logging.LoggingInterceptor=DEBUG
logging.level.org.apache.http=DEBUG
logging.level.httpclient.wire=DEBUG
logging.pattern.console=%20logger{20} - %msg%n

View File

@ -4,3 +4,4 @@ This module contains articles about Spring with Thymeleaf
## Relevant Articles: ## Relevant Articles:
- [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) - [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js)
- [Formatting Currencies in Spring Using Thymeleaf](https://www.baeldung.com/spring-thymeleaf-currencies)

View File

@ -1,4 +1,6 @@
### Relevant Articles: ### Relevant Articles:
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) - [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
- [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) - [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object)
- [Using Cookies With Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-webdriver-cookies) - [Using Cookies With Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-webdriver-cookies)
- [Clicking Elements in Selenium using JavaScript](https://www.baeldung.com/java-selenium-javascript)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Asserting Log Messages With JUnit](https://www.baeldung.com/junit-asserting-logs)