Merge pull request #5 from eugenp/master

Updating local repo
This commit is contained in:
Umang Budhwar 2020-08-23 17:28:16 +05:30 committed by GitHub
commit d175ff0b7d
241 changed files with 1494 additions and 294 deletions

View File

@ -3,6 +3,7 @@
This module contains articles about searching algorithms. This module contains articles about searching algorithms.
### Relevant articles: ### Relevant articles:
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search) - [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search) - [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search) - [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
@ -11,3 +12,4 @@ This module contains articles about searching algorithms.
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search) - [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search) - [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree) - [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -3,9 +3,11 @@
This module contains articles about Apache POI This module contains articles about Apache POI
### Relevant Articles: ### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi) - [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel) - [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow) - [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells) - [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value) - [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula) - [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)

View File

@ -9,3 +9,4 @@ This module contains articles about Java 10 core features
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler) - [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) - [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)

View File

@ -1,22 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project <project
xmlns="http://maven.apache.org/POM/4.0.0" 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"
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>
<artifactId>core-java-10</artifactId> <artifactId>core-java-10</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<name>core-java-10</name> <name>core-java-10</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung.core-java-modules</groupId>
<artifactId>parent-modules</artifactId> <artifactId>core-java-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../../</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -34,6 +41,7 @@
<properties> <properties>
<maven.compiler.source.version>10</maven.compiler.source.version> <maven.compiler.source.version>10</maven.compiler.source.version>
<maven.compiler.target.version>10</maven.compiler.target.version> <maven.compiler.target.version>10</maven.compiler.target.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,68 @@
package com.baeldung.java10.collections.conversion;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListSetConversionUnitTest {
// Set -> List; List -> Set
@Test
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(sourceSet);
}
@Test
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(sourceList);
}
@Test
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = List.copyOf(sourceSet);
}
@Test
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Set.copyOf(sourceList);
}
@Test
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = Lists.newArrayList(sourceSet);
}
@Test
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
}

View File

@ -3,7 +3,9 @@
This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java. This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java.
### Relevant Articles: ### Relevant Articles:
- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy) - [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy)
- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals) - [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals)
- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average) - [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)

View File

@ -12,3 +12,4 @@
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) - [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list) - [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)

View File

@ -10,4 +10,5 @@ This module contains articles about the Java List collection
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) - [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) - [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist) - [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2) - [[<-- Prev]](/core-java-modules/core-java-collections-list-2)

View File

@ -1,5 +1,8 @@
#Core Java Console #Core Java Console
[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output) ### Relevant Articles:
[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) - [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
- [System.console() vs. System.out](https://www.baeldung.com/java-system-console-vs-system-out)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.exceptions</groupId>
<artifactId>core-java-exceptions-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-exceptions-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.exceptions.nosuchmethoderror;
public class MainMenu {
public static void main(String[] args) {
System.out.println("Today's Specials: " + getSpecials());
}
public static String getSpecials() {
return SpecialToday.getDesert();
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.exceptions.nosuchmethoderror;
public class SpecialToday {
private static String desert = "Chocolate Cake";
public static String getDesert() {
return desert;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exceptions.nosuchmethoderror;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
class MainMenuUnitTest {
@Test
void whenGetSpecials_thenNotNull() {
assertNotNull(MainMenu.getSpecials());
}
}

View File

@ -6,4 +6,7 @@ This module contains articles about core Java input and output (IO)
- [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file) - [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file)
- [Check If a Directory Is Empty in Java](https://www.baeldung.com/java-check-empty-directory) - [Check If a Directory Is Empty in Java](https://www.baeldung.com/java-check-empty-directory)
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
- [[<-- Prev]](/core-java-modules/core-java-io-2) - [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -0,0 +1,82 @@
package com.baeldung.linenumber;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class LineAtGivenNumberUnitTest {
private static final String FILE_PATH = "src/test/resources/linesInput.txt";
@Test
public void givenFile_whenUsingBufferedReader_thenExtractedLineIsCorrect() throws IOException {
try (BufferedReader br = Files.newBufferedReader(Paths.get(FILE_PATH))) {
for (int i = 0; i < 3; i++) {
br.readLine();
}
String extractedLine = br.readLine();
assertEquals("Line 4", extractedLine);
}
}
@Test
public void givenFile_whenUsingScanner_thenExtractedLineIsCorrect() throws IOException {
try (Scanner scanner = new Scanner(new File(FILE_PATH))) {
for (int i = 0; i < 3; i++) {
scanner.nextLine();
}
String extractedLine = scanner.nextLine();
assertEquals("Line 4", extractedLine);
}
}
@Test
public void givenSmallFile_whenUsingFilesAPI_thenExtractedLineIsCorrect() throws IOException {
String extractedLine = Files.readAllLines(Paths.get(FILE_PATH)).get(4);
assertEquals("Line 5", extractedLine);
}
@Test
public void givenLargeFile_whenUsingFilesAPI_thenExtractedLineIsCorrect() throws IOException {
try (Stream<String> lines = Files.lines(Paths.get(FILE_PATH))) {
String extractedLine = lines.skip(4).findFirst().get();
assertEquals("Line 5", extractedLine);
}
}
@Test
public void givenFile_whenUsingFileUtils_thenExtractedLineIsCorrect() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("linesInput.txt").getFile());
List<String> lines = FileUtils.readLines(file, "UTF-8");
String extractedLine = lines.get(0);
assertEquals("Line 1", extractedLine);
}
@Test
public void givenFile_whenUsingIOUtils_thenExtractedLineIsCorrect() throws IOException {
String fileContent = IOUtils.toString(new FileInputStream(FILE_PATH), StandardCharsets.UTF_8);
String extractedLine = fileContent.split(System.lineSeparator())[0];
assertEquals("Line 1", extractedLine);
}
}

View File

@ -0,0 +1,5 @@
Line 1
Line 2
Line 3
Line 4
Line 5

View File

@ -10,4 +10,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout) - [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length) - [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address) - [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address)
- [List All Classes Loaded in a Specific Class Loader](https://www.baeldung.com/java-list-classes-class-loader)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm) - More articles: [[<-- prev]](/core-java-modules/core-java-jvm)

View File

@ -6,8 +6,11 @@ public interface Bar {
String method(String string); String method(String string);
default String defaultMethod() { default String defaultBar() {
return "String from Bar"; return "Default String from Bar";
} }
default String defaultCommon() {
return "Default Common from Bar";
}
} }

View File

@ -6,7 +6,11 @@ public interface Baz {
String method(String string); String method(String string);
default String defaultMethod() { default String defaultBaz() {
return "String from Baz"; return "Default String from Baz";
}
default String defaultCommon(){
return "Default Common from Baz";
} }
} }

View File

@ -5,8 +5,7 @@ package com.baeldung.java8.lambda.tips;
public interface FooExtended extends Baz, Bar { public interface FooExtended extends Baz, Bar {
@Override @Override
default String defaultMethod() { default String defaultCommon() {
return Bar.super.defaultMethod(); return Bar.super.defaultCommon();
} }
} }

View File

@ -39,9 +39,9 @@ public class Java8FunctionalInteracesLambdasUnitTest {
@Test @Test
public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() { public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
final FooExtended fooExtended = string -> string; final FooExtended fooExtended = string -> string;
final String result = fooExtended.defaultMethod(); final String result = fooExtended.defaultCommon();
assertEquals("String from Bar", result); assertEquals("Default Common from Bar", result);
} }
@Test @Test

View File

@ -4,4 +4,5 @@ This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom) - [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean) - [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [[<-- Prev]](/core-java-modules/core-java-lang-2) - [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -3,6 +3,7 @@
This module contains articles about types in Java This module contains articles about types in Java
### Relevant Articles: ### Relevant Articles:
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) - [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this) - [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes) - [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
@ -10,3 +11,4 @@ This module contains articles about types in Java
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration) - [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) - [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [Determine if an Object is of Primitive Type](https://www.baeldung.com/java-object-primitive-type)

View File

@ -12,5 +12,6 @@ This module contains articles about working with the operating system (OS) in Ja
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) - [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) - [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) - [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [Taking Screenshots Using Java](https://www.baeldung.com/java-taking-screenshots)
This module uses Java 9, so make sure to have the JDK 9 installed to run it. This module uses Java 9, so make sure to have the JDK 9 installed to run it.

View File

@ -1,3 +1,4 @@
### Relevant Articles: ### Relevant Articles:
- [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value) - [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)

View File

@ -73,7 +73,7 @@
<module>core-java-exceptions</module> <module>core-java-exceptions</module>
<module>core-java-exceptions-2</module> <module>core-java-exceptions-2</module>
<module>core-java-exceptions-3</module>
<module>core-java-function</module> <module>core-java-function</module>
<module>core-java-io</module> <module>core-java-io</module>

View File

@ -3,6 +3,7 @@
This module contains articles about Kotlin core features. This module contains articles about Kotlin core features.
### Relevant articles: ### Relevant articles:
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro) - [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro)
- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) - [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability)
- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) - [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number)
@ -10,3 +11,4 @@ This module contains articles about Kotlin core features.
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator) - [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator)
- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences) - [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) - [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Exception Handling in Kotlin](https://www.baeldung.com/kotlin/exception-handling)

View File

@ -5,3 +5,4 @@ This module contains articles about Deeplearning4j.
### Relevant Articles: ### Relevant Articles:
- [A Guide to Deeplearning4j](https://www.baeldung.com/deeplearning4j) - [A Guide to Deeplearning4j](https://www.baeldung.com/deeplearning4j)
- [Logistic Regression in Java](https://www.baeldung.com/java-logistic-regression) - [Logistic Regression in Java](https://www.baeldung.com/java-logistic-regression)
- [How to Implement a CNN with Deeplearning4j](https://www.baeldung.com/java-cnn-deeplearning4j)

View File

@ -1,3 +1,4 @@
## Relevant Articles: ## Relevant Articles:
- [Introduction to Docker Compose](https://www.baeldung.com/docker-compose) - [Introduction to Docker Compose](https://www.baeldung.com/docker-compose)
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

View File

@ -1,5 +0,0 @@
## Apache POI
This module contains articles about Apache POI
### Relevant Articles:

View File

@ -3,6 +3,8 @@
This module contains articles about conversions among Collection types and arrays in Java. This module contains articles about conversions among Collection types and arrays in Java.
### Relevant Articles: ### Relevant Articles:
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) - [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists) - [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- More articles: [[<-- prev]](../java-collections-conversions) - More articles: [[<-- prev]](../java-collections-conversions)

View File

@ -0,0 +1,32 @@
package com.baeldung.arrayconversion;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToListConversionUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = Arrays.asList(stringArray);
System.out.println(stringList);
stringList.set(0, "E");
System.out.println(stringList);
System.out.println(Arrays.toString(stringArray));
stringList.add("F");
}
@Test
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
System.out.println(stringList);
stringList.set(0, "E");
System.out.println(stringList);
System.out.println(Arrays.toString(stringArray));
stringList.add("F");
}
}

View File

@ -5,7 +5,6 @@ This module contains articles about conversions among Collection types and array
### Relevant Articles: ### Relevant Articles:
- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array) - [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array) - [Converting between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set) - [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string) - [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)
- [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map) - [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map)

View File

@ -101,42 +101,6 @@ public class JavaCollectionConversionUnitTest {
final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray); final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray);
} }
// Set -> List; List -> Set
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(sourceSet);
}
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(sourceList);
}
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = Lists.newArrayList(sourceSet);
}
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
// Map (values) -> Array, List, Set // Map (values) -> Array, List, Set
@Test @Test

3
java-numbers-4/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Probability in Java](https://www.baeldung.com/java-probability)

View File

@ -12,4 +12,4 @@ This module contains articles about Servlets.
- [Jakarta EE Servlet Exception Handling](https://www.baeldung.com/servlet-exceptions) - [Jakarta EE Servlet Exception Handling](https://www.baeldung.com/servlet-exceptions)
- [Context and Servlet Initialization Parameters](https://www.baeldung.com/context-servlet-initialization-param) - [Context and Servlet Initialization Parameters](https://www.baeldung.com/context-servlet-initialization-param)
- [The Difference between getRequestURI and getPathInfo in HttpServletRequest](https://www.baeldung.com/http-servlet-request-requesturi-pathinfo) - [The Difference between getRequestURI and getPathInfo in HttpServletRequest](https://www.baeldung.com/http-servlet-request-requesturi-pathinfo)
- Difference between request.getSession() and request.getSession(true) - [Difference between request.getSession() and request.getSession(true)](https://www.baeldung.com/java-request-getsession)

View File

@ -6,6 +6,8 @@ import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Simple snippet which shows how to add a file to the index * Simple snippet which shows how to add a file to the index
@ -14,6 +16,8 @@ import org.eclipse.jgit.lib.Repository;
*/ */
public class AddFile { public class AddFile {
private static final Logger logger = LoggerFactory.getLogger(AddFile.class);
public static void main(String[] args) throws IOException, GitAPIException { public static void main(String[] args) throws IOException, GitAPIException {
// prepare a new test-repository // prepare a new test-repository
try (Repository repository = Helper.createNewRepository()) { try (Repository repository = Helper.createNewRepository()) {
@ -29,7 +33,7 @@ public class AddFile {
.addFilepattern("testfile") .addFilepattern("testfile")
.call(); .call();
System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); logger.debug("Added file " + myfile + " to repository at " + repository.getDirectory());
} }
} }
} }

View File

@ -7,6 +7,8 @@ import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Simple snippet which shows how to commit all files * Simple snippet which shows how to commit all files
@ -15,6 +17,8 @@ import org.eclipse.jgit.lib.Repository;
*/ */
public class CommitAll { public class CommitAll {
private static final Logger logger = LoggerFactory.getLogger(CommitAll.class);
public static void main(String[] args) throws IOException, GitAPIException { public static void main(String[] args) throws IOException, GitAPIException {
// prepare a new test-repository // prepare a new test-repository
try (Repository repository = Helper.createNewRepository()) { try (Repository repository = Helper.createNewRepository()) {
@ -44,7 +48,7 @@ public class CommitAll {
.call(); .call();
System.out.println("Committed all changes to repository at " + repository.getDirectory()); logger.debug("Committed all changes to repository at " + repository.getDirectory());
} }
} }
} }

View File

@ -9,6 +9,8 @@ import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Simple snippet which shows how to create a tag * Simple snippet which shows how to create a tag
@ -17,6 +19,8 @@ import org.eclipse.jgit.revwalk.RevWalk;
*/ */
public class CreateAndDeleteTag { public class CreateAndDeleteTag {
private static final Logger logger = LoggerFactory.getLogger(CreateAndDeleteTag.class);
public static void main(String[] args) throws IOException, GitAPIException { public static void main(String[] args) throws IOException, GitAPIException {
// prepare test-repository // prepare test-repository
try (Repository repository = Helper.openJGitRepository()) { try (Repository repository = Helper.openJGitRepository()) {
@ -26,7 +30,7 @@ public class CreateAndDeleteTag {
// set it on the current HEAD // set it on the current HEAD
Ref tag = git.tag().setName("tag_for_testing").call(); Ref tag = git.tag().setName("tag_for_testing").call();
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
// remove the tag again // remove the tag again
git.tagDelete().setTags("tag_for_testing").call(); git.tagDelete().setTags("tag_for_testing").call();
@ -36,14 +40,14 @@ public class CreateAndDeleteTag {
try (RevWalk walk = new RevWalk(repository)) { try (RevWalk walk = new RevWalk(repository)) {
RevCommit commit = walk.parseCommit(id); RevCommit commit = walk.parseCommit(id);
tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
// remove the tag again // remove the tag again
git.tagDelete().setTags("tag_for_testing").call(); git.tagDelete().setTags("tag_for_testing").call();
// create an annotated tag // create an annotated tag
tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); logger.debug("Created/moved tag " + tag + " to repository at " + repository.getDirectory());
// remove the tag again // remove the tag again
git.tagDelete().setTags("tag_for_testing").call(); git.tagDelete().setTags("tag_for_testing").call();

View File

@ -7,6 +7,9 @@ import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevCommit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Simple snippet which shows how to get the commit-ids for a file to provide log information. * Simple snippet which shows how to get the commit-ids for a file to provide log information.
* *
@ -14,6 +17,8 @@ import org.eclipse.jgit.revwalk.RevCommit;
*/ */
public class Log { public class Log {
private static final Logger logger = LoggerFactory.getLogger(Log.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void main(String[] args) throws IOException, GitAPIException { public static void main(String[] args) throws IOException, GitAPIException {
try (Repository repository = Helper.openJGitRepository()) { try (Repository repository = Helper.openJGitRepository()) {
@ -22,30 +27,30 @@ public class Log {
.call(); .call();
int count = 0; int count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits overall on current branch"); logger.debug("Had " + count + " commits overall on current branch");
logs = git.log() logs = git.log()
.add(repository.resolve(git.getRepository().getFullBranch())) .add(repository.resolve(git.getRepository().getFullBranch()))
.call(); .call();
count = 0; count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); logger.debug("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log() logs = git.log()
.all() .all()
.call(); .call();
count = 0; count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits overall in repository"); logger.debug("Had " + count + " commits overall in repository");
logs = git.log() logs = git.log()
// for all log.all() // for all log.all()
@ -53,10 +58,10 @@ public class Log {
.call(); .call();
count = 0; count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits on README.md"); logger.debug("Had " + count + " commits on README.md");
logs = git.log() logs = git.log()
// for all log.all() // for all log.all()
@ -64,10 +69,10 @@ public class Log {
.call(); .call();
count = 0; count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
//System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); logger.trace("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits on pom.xml"); logger.debug("Had " + count + " commits on pom.xml");
} }
} }
} }

View File

@ -13,5 +13,6 @@ public class PorcelainUnitTest {
CreateAndDeleteTag.main(null); CreateAndDeleteTag.main(null);
Log.main(null); Log.main(null);
} }
} }

View File

@ -6,3 +6,4 @@ This module contains articles about the Java Microbenchmark Harness (JMH).
- [Microbenchmarking with Java](https://www.baeldung.com/java-microbenchmark-harness) - [Microbenchmarking with Java](https://www.baeldung.com/java-microbenchmark-harness)
- [A Guide to False Sharing and @Contended](https://www.baeldung.com/java-false-sharing-contended) - [A Guide to False Sharing and @Contended](https://www.baeldung.com/java-false-sharing-contended)
- [Performance Comparison of boolean[] vs BitSet](https://www.baeldung.com/java-boolean-array-bitset-performance)

View File

@ -3,5 +3,7 @@
This module contains articles about JSON. This module contains articles about JSON.
### Relevant Articles: ### Relevant Articles:
- [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter) - [Introduction to Jsoniter](https://www.baeldung.com/java-jsoniter)
- [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi) - [Introduction to Moshi Json](https://www.baeldung.com/java-json-moshi)
- [Hypermedia Serialization With JSON-LD](https://www.baeldung.com/json-linked-data)

View File

@ -5,6 +5,7 @@ This module contains articles about jsoup.
### Relevant Articles: ### Relevant Articles:
- [Parsing HTML in Java with Jsoup](https://www.baeldung.com/java-with-jsoup) - [Parsing HTML in Java with Jsoup](https://www.baeldung.com/java-with-jsoup)
- [How to add proxy support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy) - [How to add proxy support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy)
- [Preserving Line Breaks When Using Jsoup](https://www.baeldung.com/jsoup-line-breaks)
### Build the Project ### Build the Project

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project 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"
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>
<artifactId>libraries-testing</artifactId> <artifactId>libraries-testing</artifactId>
<name>libraries-testing</name> <name>libraries-testing</name>
@ -158,6 +158,13 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<version>${archunit.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -193,7 +200,7 @@
<properties> <properties>
<asciidoctor.version>1.5.7.1</asciidoctor.version> <asciidoctor.version>1.5.7.1</asciidoctor.version>
<serenity.version>1.9.9</serenity.version> <serenity.version>1.9.9</serenity.version>
<serenity.jbehave.version>1.9.0</serenity.jbehave.version> <serenity.jbehave.version>1.9.0</serenity.jbehave.version>
<serenity.jira.version>1.9.0</serenity.jira.version> <serenity.jira.version>1.9.0</serenity.jira.version>
<serenity.plugin.version>1.9.27</serenity.plugin.version> <serenity.plugin.version>1.9.27</serenity.plugin.version>
@ -210,6 +217,7 @@
<maven-compiler-plugin.target>1.8</maven-compiler-plugin.target> <maven-compiler-plugin.target>1.8</maven-compiler-plugin.target>
<maven-compiler-plugin.source>1.8</maven-compiler-plugin.source> <maven-compiler-plugin.source>1.8</maven-compiler-plugin.source>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<archunit.version>0.14.1</archunit.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,38 @@
package com.baeldung.archunit.smurfs.persistence;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import com.baeldung.archunit.smurfs.persistence.domain.Smurf;
import static java.util.stream.Collectors.toList;
public class SmurfsRepository {
private static Map<String,Smurf> smurfs = Collections.synchronizedMap(new TreeMap<>());
static {
// Just a few here. A full list can be found
// at https://smurfs.fandom.com/wiki/List_of_Smurf_characters
smurfs.put("Papa", new Smurf("Papa", true, true));
smurfs.put("Actor", new Smurf("Actor", true, true));
smurfs.put("Alchemist", new Smurf("Alchemist", true, true));
smurfs.put("Archeologist", new Smurf("Archeologist", true, true));
smurfs.put("Architect", new Smurf("Architect", true, true));
smurfs.put("Baby", new Smurf("Baby", true, true));
smurfs.put("Baker", new Smurf("Baker", true, true));
smurfs.put("Baker", new Smurf("Baker", true, true));
}
public List<Smurf> findAll() {
return Collections.unmodifiableList(smurfs.values().stream().collect(toList()));
}
public Optional<Smurf> findByName(String name) {
return Optional.of(smurfs.get(name));
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.archunit.smurfs.persistence.domain;
public class Smurf {
private String name;
private boolean comic;
private boolean cartoon;
public Smurf() {}
public Smurf(String name, boolean comic, boolean cartoon) {
this.name = name;
this.comic = comic;
this.cartoon = cartoon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isComic() {
return comic;
}
public void setCommic(boolean comic) {
this.comic = comic;
}
public boolean isCartoon() {
return cartoon;
}
public void setCartoon(boolean cartoon) {
this.cartoon = cartoon;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.archunit.smurfs.presentation;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.archunit.smurfs.service.SmurfsService;
import com.baeldung.archunit.smurfs.service.dto.SmurfDTO;
@RequestMapping(value = "/smurfs", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class SmurfsController {
private SmurfsService smurfs;
public SmurfsController(SmurfsService smurfs) {
this.smurfs = smurfs;
}
@GetMapping
public List<SmurfDTO> getSmurfs() {
return smurfs.findAll();
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.archunit.smurfs.service;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
import com.baeldung.archunit.smurfs.persistence.SmurfsRepository;
import com.baeldung.archunit.smurfs.persistence.domain.Smurf;
import com.baeldung.archunit.smurfs.service.dto.SmurfDTO;
@Component
public class SmurfsService {
private SmurfsRepository repository;
public SmurfsService(SmurfsRepository repository) {
this.repository = repository;
}
public List<SmurfDTO> findAll() {
return repository.findAll()
.stream()
.map(SmurfsService::toDTO)
.collect(Collectors.toList());
}
public static SmurfDTO toDTO(Smurf smurf) {
return new SmurfDTO(smurf.getName(),smurf.isComic(), smurf.isCartoon());
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.archunit.smurfs.service.dto;
public class SmurfDTO {
private String name;
private boolean comic;
private boolean cartoon;
public SmurfDTO() {}
public SmurfDTO(String name, boolean comic, boolean cartoon) {
this.name = name;
this.comic = comic;
this.cartoon = cartoon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isComic() {
return comic;
}
public void setCommic(boolean comic) {
this.comic = comic;
}
public boolean isCartoon() {
return cartoon;
}
public void setCartoon(boolean cartoon) {
this.cartoon = cartoon;
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.archunit.smurfs;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.library.Architectures.LayeredArchitecture;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class SmurfsArchUnitTest {
@Test
public void givenPresentationLayerClasses_thenWrongCheckFails() {
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
ArchRule r1 = classes()
.that()
.resideInAPackage("..presentation..")
.should().onlyDependOnClassesThat()
.resideInAPackage("..service..");
assertThrows(AssertionError.class, ()-> r1.check(jc)) ;
}
@Test
public void givenPresentationLayerClasses_thenCheckWithFrameworkDependenciesSuccess() {
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
ArchRule r1 = classes()
.that()
.resideInAPackage("..presentation..")
.should().onlyDependOnClassesThat()
.resideInAnyPackage("..service..", "java..", "javax..", "org.springframework..");
r1.check(jc);
}
@Test
public void givenPresentationLayerClasses_thenNoPersistenceLayerAccess() {
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
ArchRule r1 = noClasses()
.that()
.resideInAPackage("..presentation..")
.should().dependOnClassesThat()
.resideInAPackage("..persistence..");
r1.check(jc);
}
@Test
public void givenApplicationClasses_thenNoLayerViolationsShouldExist() {
JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs");
LayeredArchitecture arch = layeredArchitecture()
// Define layers
.layer("Presentation").definedBy("..presentation..")
.layer("Service").definedBy("..service..")
.layer("Persistence").definedBy("..persistence..")
// Add constraints
.whereLayer("Presentation").mayNotBeAccessedByAnyLayer()
.whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
arch.check(jc);
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.dbunit" level="INFO" />
</configuration>

View File

@ -1,3 +1,3 @@
### Relevant Articles: ### Relevant Articles:
- Optional Dependency in Maven - [Optional Dependency in Maven](https://www.baeldung.com/maven-optional-dependency)

View File

@ -4,3 +4,4 @@
- [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) - [Open/Closed Principle in Java](https://www.baeldung.com/java-open-closed-principle)
- [Interface Segregation Principle in Java](https://www.baeldung.com/java-interface-segregation) - [Interface Segregation Principle in Java](https://www.baeldung.com/java-interface-segregation)
- [Liskov Substitution Principle in Java](https://www.baeldung.com/java-liskov-substitution-principle)

View File

@ -5,6 +5,7 @@ This module contains articles about performance testing.
### Relevant Articles: ### Relevant Articles:
- [Performance of Java Mapping Frameworks](https://www.baeldung.com/java-performance-mapping-frameworks) - [Performance of Java Mapping Frameworks](https://www.baeldung.com/java-performance-mapping-frameworks)
- [Performance Effects of Exceptions in Java](https://www.baeldung.com/java-exceptions-performance)
### Running ### Running

View File

@ -19,27 +19,14 @@
<version>${orika.version}</version> <version>${orika.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.sf.dozer</groupId> <groupId>com.github.dozermapper</groupId>
<artifactId>dozer</artifactId> <artifactId>dozer-core</artifactId>
<version>${dozer.version}</version> <version>${dozer.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.craftsman</groupId>
<artifactId>dozer-jdk8-support</artifactId>
<version>${dozer-jdk8-support.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.mapstruct</groupId> <groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId> <artifactId>mapstruct</artifactId>
<version>${mapstruct-jdk8.version}</version> <version>${mapstruct.version}</version>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct-jdk8.version}</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -77,10 +64,15 @@
<source>${javac.target}</source> <source>${javac.target}</source>
<target>${javac.target}</target> <target>${javac.target}</target>
<annotationProcessorPaths> <annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
<path> <path>
<groupId>org.mapstruct</groupId> <groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId> <artifactId>mapstruct-processor</artifactId>
<version>${mapstruct-processor.version}</version> <version>${mapstruct.version}</version>
</path> </path>
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>
@ -120,28 +112,16 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<mainClass>com.baeldung.performancetests.MappingFrameworksPerformance</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>2.5</version> <version>${clean.plugin.version}</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version> <version>${deploy.plugin.version}</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-install-plugin</artifactId> <artifactId>maven-install-plugin</artifactId>
@ -179,18 +159,12 @@
<!-- <!--
JMH version to use with this project. JMH version to use with this project.
--> -->
<jmh.version>1.21</jmh.version> <jmh.version>1.23</jmh.version>
<orika.version>1.5.2</orika.version> <orika.version>1.5.4</orika.version>
<dozer.version>5.5.1</dozer.version> <dozer.version>6.5.0</dozer.version>
<dozer-jdk8-support.version>1.0.2</dozer-jdk8-support.version> <mapstruct.version>1.3.1.Final</mapstruct.version>
<mapstruct-jdk8.version>1.2.0.Final</mapstruct-jdk8.version> <modelmapper.version>2.3.8</modelmapper.version>
<modelmapper.version>1.1.0</modelmapper.version> <jmapper.version>1.6.1.CR2</jmapper.version>
<jmapper.version>1.6.0.1</jmapper.version>
<mapstruct-processor.version>1.2.0.Final</mapstruct-processor.version>
<jmh-core.version>1.21</jmh-core.version>
<jmh-generator.version>1.21</jmh-generator.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
<!-- <!--
Java source/target to use for compilation. Java source/target to use for compilation.
@ -201,14 +175,16 @@
Name of the benchmark Uber-JAR to generate. Name of the benchmark Uber-JAR to generate.
--> -->
<uberjar.name>benchmarks</uberjar.name> <uberjar.name>benchmarks</uberjar.name>
<compiler.plugin.version>3.1</compiler.plugin.version> <clean.plugin.version>3.1.0</clean.plugin.version>
<shade.plugin.version>2.2</shade.plugin.version> <deploy.plugin.version>3.0.0-M1</deploy.plugin.version>
<install.version>2.5.1</install.version> <compiler.plugin.version>3.8.1</compiler.plugin.version>
<jar.plugin.version>2.4</jar.plugin.version> <shade.plugin.version>3.2.4</shade.plugin.version>
<javadoc.plugin.version>2.9.1</javadoc.plugin.version> <install.version>3.0.0-M1</install.version>
<resources.plugin.version>2.6</resources.plugin.version> <jar.plugin.version>3.2.0</jar.plugin.version>
<site.plugin.version>3.3</site.plugin.version> <javadoc.plugin.version>3.2.0</javadoc.plugin.version>
<source.plugin.version>2.2.1</source.plugin.version> <resources.plugin.version>3.1.0</resources.plugin.version>
<site.plugin.version>3.9.1</site.plugin.version>
<source.plugin.version>3.2.1</source.plugin.version>
<surefire.plugin.version>2.17</surefire.plugin.version> <surefire.plugin.version>2.17</surefire.plugin.version>
</properties> </properties>

View File

@ -2,28 +2,28 @@ package com.baeldung.performancetests.dozer;
import com.baeldung.performancetests.Converter; import com.baeldung.performancetests.Converter;
import com.baeldung.performancetests.model.destination.DestinationCode; import com.baeldung.performancetests.model.destination.DestinationCode;
import com.baeldung.performancetests.model.destination.Order;
import com.baeldung.performancetests.model.source.SourceCode; import com.baeldung.performancetests.model.source.SourceCode;
import com.baeldung.performancetests.model.source.SourceOrder; import com.baeldung.performancetests.model.source.SourceOrder;
import com.baeldung.performancetests.model.destination.Order; import com.github.dozermapper.core.DozerBeanMapperBuilder;
import org.dozer.DozerBeanMapper; import com.github.dozermapper.core.Mapper;
import org.dozer.Mapper;
public class DozerConverter implements Converter { public class DozerConverter implements Converter {
private final Mapper mapper; private final Mapper mapper;
public DozerConverter() { public DozerConverter() {
DozerBeanMapper mapper = new DozerBeanMapper(); this.mapper = DozerBeanMapperBuilder.create()
mapper.addMapping(DozerConverter.class.getResourceAsStream("/dozer-mapping.xml")); .withMappingFiles("dozer-mapping.xml")
this.mapper = mapper; .build();
}
@Override
public Order convert(SourceOrder sourceOrder) {
return mapper.map(sourceOrder,Order.class);
}
@Override
public DestinationCode convert(SourceCode sourceCode) {
return mapper.map(sourceCode, DestinationCode.class);
}
} }
@Override
public Order convert(SourceOrder sourceOrder) {
return mapper.map(sourceOrder, Order.class);
}
@Override
public DestinationCode convert(SourceCode sourceCode) {
return mapper.map(sourceCode, DestinationCode.class);
}
}

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" <mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping https://dozermapper.github.io/schema/bean-mapping.xsd">
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<configuration> <configuration>
<stop-on-errors>true</stop-on-errors> <stop-on-errors>true</stop-on-errors>

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" <mappings xmlns="http://dozermapper.github.io/schema/bean-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://dozermapper.github.io/schema/bean-mapping https://dozermapper.github.io/schema/bean-mapping.xsd">
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<configuration> <configuration>
<stop-on-errors>true</stop-on-errors> <stop-on-errors>true</stop-on-errors>

View File

@ -13,3 +13,4 @@
- [Returning the Generated Keys in JDBC](https://www.baeldung.com/jdbc-returning-generated-keys) - [Returning the Generated Keys in JDBC](https://www.baeldung.com/jdbc-returning-generated-keys)
- [Loading JDBC Drivers](https://www.baeldung.com/java-jdbc-loading-drivers) - [Loading JDBC Drivers](https://www.baeldung.com/java-jdbc-loading-drivers)
- [Difference Between Statement and PreparedStatement](https://www.baeldung.com/java-statement-preparedstatement) - [Difference Between Statement and PreparedStatement](https://www.baeldung.com/java-statement-preparedstatement)
- [Extracting Database Metadata Using JDBC](https://www.baeldung.com/jdbc-database-metadata)

View File

@ -1 +1,3 @@
### Relevant Articles: ### Relevant Articles:
- [Flyway Repair With Spring Boot](https://www.baeldung.com/spring-boot-flyway-repair)

View File

@ -13,3 +13,4 @@ This module contains articles about Hibernate 5. Let's not add more articles her
- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) - [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager)
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
- [What Is the Hi/Lo Algorithm?](https://www.baeldung.com/hi-lo-algorithm-hibernate)

View File

@ -0,0 +1,34 @@
package com.baeldung.hibernate.hilo;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class RestaurantOrder {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilo_sequence_generator")
@GenericGenerator(
name = "hilo_sequence_generator",
strategy = "sequence",
parameters = {
@Parameter(name = "sequence_name", value = "hilo_seqeunce"),
@Parameter(name = "initial_value", value = "1"),
@Parameter(name = "increment_size", value = "3"),
@Parameter(name = "optimizer", value = "hilo")
}
)
private Long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.hibernate.hilo;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import static org.junit.Assert.fail;
public class HibernateHiloUnitTest {
private Session session;
@Before
public void init() {
try {
configureLogger();
ServiceRegistry serviceRegistry = configureServiceRegistry();
SessionFactory factory = getSessionFactoryBuilder(serviceRegistry).build();
session = factory.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
private void configureLogger() {
BasicConfigurator.configure();
LogManager.getLogger("org.hibernate").setLevel(Level.ERROR);
LogManager.getLogger("org.hibernate.id.enhanced.SequenceStructure").setLevel(Level.DEBUG);
LogManager.getLogger("org.hibernate.event.internal.AbstractSaveEventListener").setLevel(Level.DEBUG);
LogManager.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(RestaurantOrder.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = getPropertiesURL();
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
private static URL getPropertiesURL() {
return Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate-hilo.properties");
}
@Test
public void givenHiLoAlgorithm_when9EntitiesArePersisted_Then3callsToDBForNextValueShouldBeMade() {
Transaction transaction = session.beginTransaction();
for (int i = 0; i < 9; i++) {
session.persist(new RestaurantOrder());
session.flush();
}
transaction.commit();
}
@After
public void cleanup() {
session.close();
}
}

View File

@ -0,0 +1,10 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:hilo_db;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800

View File

@ -1,3 +1,7 @@
## JPA in Java ## JPA in Java
This module contains articles about the Java Persistence API (JPA) in Java. This module contains articles about the Java Persistence API (JPA) in Java.
### Relevant Articles:
- [JPA Entity Equality](https://www.baeldung.com/jpa-entity-equality)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Spring Data Azure Cosmos DB](https://www.baeldung.com/spring-data-cosmos-db)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Spring Data JDBC](https://www.baeldung.com/spring-data-jdbc-intro)

View File

@ -0,0 +1,16 @@
## Spring Data JPA - Query
This module contains articles about querying data using Spring Data JPA
### Relevant Articles:
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
- More articles: [[<-- prev]](../spring-data-jpa-query)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-query</artifactId>
<name>spring-data-jpa-query-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,9 +1,9 @@
package com.baeldung.persistence.dao; package com.baeldung.persistence.dao;
import java.util.List;
import com.baeldung.persistence.model.Book; import com.baeldung.persistence.model.Book;
import java.util.List;
public interface BookRepositoryCustom { public interface BookRepositoryCustom {
List<Book> findBooksByAuthorNameAndTitle(String authorName, String title); List<Book> findBooksByAuthorNameAndTitle(String authorName, String title);

View File

@ -1,7 +1,7 @@
package com.baeldung.persistence.dao; package com.baeldung.persistence.dao;
import java.util.ArrayList; import com.baeldung.persistence.model.Book;
import java.util.List; import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
@ -9,9 +9,8 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import java.util.ArrayList;
import com.baeldung.persistence.model.Book; import java.util.List;
import org.springframework.stereotype.Repository;
@Repository @Repository
public class BookRepositoryImpl implements BookRepositoryCustom { public class BookRepositoryImpl implements BookRepositoryCustom {

View File

@ -1,14 +1,14 @@
package com.baeldung.persistence.dao; package com.baeldung.persistence.dao;
import static com.baeldung.persistence.dao.BookSpecifications.hasAuthor;
import static com.baeldung.persistence.dao.BookSpecifications.titleContains;
import static org.springframework.data.jpa.domain.Specifications.where;
import java.util.List;
import com.baeldung.persistence.model.Book; import com.baeldung.persistence.model.Book;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
import static com.baeldung.persistence.dao.BookSpecifications.hasAuthor;
import static com.baeldung.persistence.dao.BookSpecifications.titleContains;
import static org.springframework.data.jpa.domain.Specification.where;
@Service @Service
public class BookService { public class BookService {

View File

@ -11,6 +11,7 @@ This module contains articles about querying data using Spring Data JPA
- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example)
- [JPA Join Types](https://www.baeldung.com/jpa-join-types) - [JPA Join Types](https://www.baeldung.com/jpa-join-types)
- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) - [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs)
- More articles: [[more -->]](../spring-data-jpa-query-2)
### Eclipse Config ### Eclipse Config
After importing the project into Eclipse, you may see the following error: After importing the project into Eclipse, you may see the following error:

View File

@ -7,7 +7,6 @@
- [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)
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
- More articles: [[next -->]](/spring-jpa-2) - More articles: [[next -->]](/spring-jpa-2)
### Eclipse Config ### Eclipse Config

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Jess Rule Engine and JSR 94](https://www.baeldung.com/java-rule-engine-jess-jsr-94)

View File

@ -11,3 +11,4 @@ This module contains articles about Spring Security 5
- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver)
- [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile) - [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile)
- [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout) - [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout)
- [How to Disable Spring Security Logout Redirects](https://www.baeldung.com/spring-security-disable-logout-redirects)

View File

@ -1,3 +0,0 @@
## Spring All
This module contains articles about Spring

View File

@ -1,61 +0,0 @@
package org.baeldung.scopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@ComponentScan("org.baeldung.scopes")
@EnableWebMvc
public class ScopesConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator applicationScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator websocketScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
}

View File

@ -56,6 +56,7 @@
<module>spring-boot-performance</module> <module>spring-boot-performance</module>
<module>spring-boot-properties</module> <module>spring-boot-properties</module>
<module>spring-boot-properties-2</module> <module>spring-boot-properties-2</module>
<module>spring-boot-properties-3</module>
<module>spring-boot-property-exp</module> <module>spring-boot-property-exp</module>
<module>spring-boot-runtime</module> <module>spring-boot-runtime</module>
<module>spring-boot-security</module> <module>spring-boot-security</module>

View File

@ -43,6 +43,9 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.probes.ProbesApplication</mainClass>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>

View File

@ -0,0 +1,30 @@
package com.baeldung.health;
import org.springframework.boot.actuate.health.HttpCodeStatusMapper;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;
@Component
public class CustomStatusCodeMapper implements HttpCodeStatusMapper {
@Override
public int getStatusCode(Status status) {
if (status == Status.DOWN) {
return 500;
}
if (status == Status.OUT_OF_SERVICE) {
return 503;
}
if (status == Status.UNKNOWN) {
return 500;
}
if (status.getCode().equals("WARNING")) {
return 500;
}
return 200;
}
}

View File

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

View File

@ -0,0 +1,30 @@
package com.baeldung.health;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
@Component
@ConditionalOnEnabledHealthIndicator("random")
public class RandomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
double chance = ThreadLocalRandom.current().nextDouble();
Health.Builder status = Health.up();
if (chance > 0.9) {
status = Health.down(new RuntimeException("Bad Luck"));
}
Map<String, Object> details = new HashMap<>();
details.put("chance", chance);
details.put("strategy", "thread-local");
return status.withDetails(details).build();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.health;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class WarningHealthIndicator implements HealthIndicator {
@Override
public Health health() {
return Health.status("WARNING").build();
}
}

View File

@ -1 +1,5 @@
management.health.probes.enabled=true management.health.probes.enabled=true
management.endpoint.health.show-details=always
management.endpoint.health.status.http-mapping.down=500
management.endpoint.health.status.http-mapping.out_of_service=503
management.endpoint.health.status.http-mapping.warning=500

View File

@ -0,0 +1,26 @@
package com.baeldung.health;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = "management.health.random.enabled=false")
class DisabledRandomHealthIndicatorIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void givenADisabledIndicator_whenSendingRequest_thenReturns404() throws Exception {
mockMvc.perform(get("/actuator/health/random"))
.andExpect(status().isNotFound());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.health;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@SpringBootTest
@AutoConfigureMockMvc
class RandomHealthIndicatorIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void givenRandomIndicator_whenCallingTheAPI_thenReturnsExpectedDetails() throws Exception {
mockMvc.perform(get("/actuator/health/random"))
.andExpect(jsonPath("$.status").exists())
.andExpect(jsonPath("$.details.strategy").value("thread-local"))
.andExpect(jsonPath("$.details.chance").exists());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.health;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class WarningHealthIndicatorIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void givenCustomMapping_whenCallingTheAPI_thenTheStatusCodeIsAsExpected() throws Exception {
mockMvc.perform(get("/actuator/health/warning"))
.andExpect(jsonPath("$.status").value("WARNING"))
.andExpect(status().isInternalServerError());
}
}

View File

@ -20,7 +20,7 @@ public class User {
@Max(value = 65, message = "Age should not be greater than 65") @Max(value = 65, message = "Age should not be greater than 65")
private int age; private int age;
@Email(regexp=".@.\\..*", message = "Email should be valid") @Email(regexp=".*@.*\\..*", message = "Email should be valid")
private String email; private String email;
public Long getId() { public Long getId() {

View File

@ -0,0 +1,9 @@
## Spring Boot Properties
### Relevant Articles:
- [How to Define a Map in YAML for a POJO?](https://www.baeldung.com/yaml-map-pojo)

View File

@ -0,0 +1,51 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<artifactId>spring-boot-properties-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-properties-3</name>
<description>Spring Boot Properties Module</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
</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,16 @@
package com.baeldung.boot.properties;
import com.baeldung.boot.properties.config.TshirtSizeConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(TshirtSizeConfig.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.boot.properties.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;
@ConfigurationProperties(prefix = "t-shirt-size")
public class TshirtSizeConfig {
private final Map<String, Integer> simpleMapping;
private final Map<String, Map<String, Integer>> complexMapping;
public TshirtSizeConfig(Map<String, Integer> simpleMapping, Map<String, Map<String, Integer>> complexMapping) {
this.simpleMapping = simpleMapping;
this.complexMapping = complexMapping;
}
public Map<String, Integer> getSimpleMapping() {
return simpleMapping;
}
public Map<String, Map<String, Integer>> getComplexMapping() {
return complexMapping;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.boot.properties.controller;
import org.springframework.web.bind.annotation.*;
import com.baeldung.boot.properties.service.SizeConverterService;
@RestController
@RequestMapping(value = "/")
public class TshirtSizeController {
private final SizeConverterService service;
public TshirtSizeController(SizeConverterService service) {
this.service = service;
}
@RequestMapping(value ="convertSize", method = RequestMethod.GET)
public int convertSize(@RequestParam(value = "label") final String label, @RequestParam(value = "countryCode", required = false) final String countryCode) {
return service.convertSize(label, countryCode);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.boot.properties.service;
import org.springframework.stereotype.Service;
import com.baeldung.boot.properties.config.TshirtSizeConfig;
@Service
public class SizeConverterImpl implements SizeConverterService {
private final TshirtSizeConfig tshirtSizeConfig;
public SizeConverterImpl(TshirtSizeConfig tshirtSizeConfig) {
this.tshirtSizeConfig = tshirtSizeConfig;
}
public int convertSize(String label, String countryCode) {
if(countryCode == null) {
return tshirtSizeConfig.getSimpleMapping().get(label);
}
return tshirtSizeConfig.getComplexMapping().get(label).get(countryCode.toLowerCase());
}
}

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