diff --git a/README.md b/README.md index 8ff04d8fc5..1d916c8409 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,9 @@ CI - Jenkins ================================ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)** +### Relevant Articles: +================================ + +- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) +- [Apache Maven Tutorial](http://www.baeldung.com/maven) +- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) diff --git a/algorithms/README.md b/algorithms/README.md index b3e11de6c5..50cdfbbd4f 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -20,4 +20,5 @@ - [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze) - [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) -- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) \ No newline at end of file +- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) +- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) diff --git a/asciidoctor/README.md b/asciidoctor/README.md index 3c602b6abd..aafd0bca17 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -2,3 +2,4 @@ - [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) - [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) +- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor) diff --git a/aws/README.md b/aws/README.md index 95de3c8464..d23937a419 100644 --- a/aws/README.md +++ b/aws/README.md @@ -8,4 +8,5 @@ - [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload) - [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests) - [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3) +- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java) diff --git a/cdi/pom.xml b/cdi/pom.xml index 74ba52ea8d..00cc96a7ed 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -8,16 +8,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring - - org.springframework - spring-core - ${spring.version} - org.springframework spring-context diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index 0126e96758..9076e63642 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -28,12 +28,6 @@ groovy-sql ${groovy-sql.version} - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - org.junit.platform junit-platform-runner diff --git a/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java b/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java new file mode 100644 index 0000000000..60e55ef422 --- /dev/null +++ b/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.java10; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class Java10FeaturesUnitTest { + + private List someIntList; + + @Before + public void setup() { + someIntList = new ArrayList<>(); + + someIntList.add(1); + someIntList.add(2); + someIntList.add(3); + } + + @Test + public void whenVarInitWithString_thenGetStringTypeVar() { + var message = "Hello, Java 10"; + assertTrue(message instanceof String); + } + + @Test + public void whenVarInitWithAnonymous_thenGetAnonymousType() { + var obj = new Object() {}; + assertFalse(obj.getClass().equals(Object.class)); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenModifyCopyOfList_thenThrowsException() { + List copyList = List.copyOf(someIntList); + copyList.add(4); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenModifyToUnmodifiableList_thenThrowsException() { + List evenList = someIntList.stream() + .filter(i -> i % 2 == 0) + .collect(Collectors.toUnmodifiableList()); + evenList.add(4); + } + + @Test + public void whenListContainsInteger_OrElseThrowReturnsInteger() { + Integer firstEven = someIntList.stream() + .filter(i -> i % 2 == 0) + .findFirst() + .orElseThrow(); + is(firstEven).equals(Integer.valueOf(2)); + } +} diff --git a/core-java-8/README.md b/core-java-8/README.md index f3287651e1..f0d7818f5b 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -47,3 +47,7 @@ - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) +- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) + diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 7b49772309..aab349781a 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -9,17 +9,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 4973b8e837..c5d3396642 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -8,10 +8,11 @@ core-java-collections - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + @@ -25,11 +26,6 @@ collections-generic ${collections-generic.version} - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 @@ -55,7 +51,6 @@ - 22.0 3.5 4.1 4.01 diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml index 829c511143..7e162abc64 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency/pom.xml @@ -9,17 +9,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index 9fcca6c590..1437b85ac2 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -9,8 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -20,11 +21,6 @@ collections-generic ${collections-generic.version} - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index aaffac5e38..3fd8e80296 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -19,11 +20,6 @@ collections-generic ${collections-generic.version} - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/core-java/README.md b/core-java/README.md index 14bd26e821..8a94c9de8e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -140,3 +140,9 @@ - [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) - [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) - [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) +- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) +- [Sending Emails with Java](http://www.baeldung.com/java-email) +- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) +- [Java KeyStore API](http://www.baeldung.com/java-keystore) +- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) diff --git a/core-java/pom.xml b/core-java/pom.xml index 74a4fa1f75..88fae5edea 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -9,17 +9,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - - com.google.guava - guava - ${guava.version} - commons-io commons-io @@ -438,7 +433,6 @@ 1.2.17 - 22.0 3.5 1.55 1.10 diff --git a/core-java/src/main/java/com/baeldung/designpatterns/composite/CompositeDemo.java b/core-java/src/main/java/com/baeldung/designpatterns/composite/CompositeDemo.java new file mode 100644 index 0000000000..9537dd0d2b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/composite/CompositeDemo.java @@ -0,0 +1,19 @@ +package com.baeldung.designpatterns.composite; + +/** + * Created by Gebruiker on 5/3/2018. + */ +public class CompositeDemo { + + public static void main(String args[]) { + Department salesDepartment = new SalesDepartment(1, "Sales department"); + Department financialDepartment = new FinancialDepartment(2, "Financial department"); + + HeadDepartment headDepartment = new HeadDepartment(3, "Head department"); + + headDepartment.addDepartMent(salesDepartment); + headDepartment.addDepartMent(financialDepartment); + + headDepartment.printDepartmentName(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/composite/Department.java b/core-java/src/main/java/com/baeldung/designpatterns/composite/Department.java new file mode 100644 index 0000000000..82fa3a3efc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/composite/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.composite; + +/** + * Created by Gebruiker on 5/1/2018. + */ +public interface Department { + + void printDepartmentName(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/composite/FinancialDepartment.java b/core-java/src/main/java/com/baeldung/designpatterns/composite/FinancialDepartment.java new file mode 100644 index 0000000000..dc5a2bb9d9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/composite/FinancialDepartment.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.composite; + +/** + * Created by Gebruiker on 5/1/2018. + */ +public class FinancialDepartment implements Department { + + private Integer id; + private String name; + + public FinancialDepartment(Integer id, String name) { + this.id = id; + this.name = name; + } + + public void printDepartmentName() { + System.out.println(getClass().getSimpleName()); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/composite/HeadDepartment.java b/core-java/src/main/java/com/baeldung/designpatterns/composite/HeadDepartment.java new file mode 100644 index 0000000000..119b9c76b5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/composite/HeadDepartment.java @@ -0,0 +1,33 @@ +package com.baeldung.designpatterns.composite; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Gebruiker on 5/1/2018. + */ +public class HeadDepartment implements Department { + + private Integer id; + private String name; + + private List childDepartments; + + public HeadDepartment(Integer id, String name) { + this.id = id; + this.name = name; + this.childDepartments = new ArrayList(); + } + + public void printDepartmentName() { + childDepartments.forEach(Department::printDepartmentName); + } + + public void addDepartMent(Department department) { + childDepartments.add(department); + } + + public void removeDepartment(Department department) { + childDepartments.remove(department); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/composite/SalesDepartment.java b/core-java/src/main/java/com/baeldung/designpatterns/composite/SalesDepartment.java new file mode 100644 index 0000000000..af234b4915 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/composite/SalesDepartment.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.composite; + +/** + * Created by Gebruiker on 5/1/2018. + */ +public class SalesDepartment implements Department { + + private Integer id; + private String name; + + public SalesDepartment(Integer id, String name) { + this.id = id; + this.name = name; + } + + public void printDepartmentName() { + System.out.println(getClass().getSimpleName()); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index d923ec698c..00c3ac188d 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -25,12 +25,6 @@ commons-math3 ${commons-math3.version} - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - org.junit.platform junit-platform-runner diff --git a/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt new file mode 100644 index 0000000000..6dc9b95f1f --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt @@ -0,0 +1,19 @@ +package com.baeldung.filesystem + +import java.io.File + +class FileWriter { + + fun writeFileUsingPrintWriter(fileName: String, fileContent: String) = + File(fileName).printWriter().use { out -> out.print(fileContent) } + + fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) = + File(fileName).bufferedWriter().use { out -> out.write(fileContent) } + + fun writeFileDirectly(fileName: String, fileContent: String) = + File(fileName).writeText(fileContent) + + fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) = + File(fileName).writeBytes(fileContent.toByteArray()) + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt new file mode 100644 index 0000000000..91c66a4fee --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.filesystem + +import org.junit.jupiter.api.Test +import java.io.File +import kotlin.test.assertEquals + +internal class FileWriterTest { + + private val fileName = "src/test/resources/Kotlin.out" + + private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly" + + private val fileWriter = FileWriter() + + @Test + fun whenWrittenWithPrintWriter_thenCorrect() { + fileWriter.writeFileUsingPrintWriter(fileName, fileContent) + + assertEquals(fileContent, File(fileName).readText()) + } + + @Test + fun whenWrittenWithBufferedWriter_thenCorrect() { + fileWriter.writeFileUsingBufferedWriter(fileName, fileContent) + + assertEquals(fileContent, File(fileName).readText()) + } + + @Test + fun whenWrittenDirectly_thenCorrect() { + fileWriter.writeFileDirectly(fileName, fileContent) + + assertEquals(fileContent, File(fileName).readText()) + } + + @Test + fun whenWrittenDirectlyAsBytes_thenCorrect() { + fileWriter.writeFileDirectlyAsBytes(fileName, fileContent) + + assertEquals(fileContent, File(fileName).readText()) + } + +} \ No newline at end of file diff --git a/drools/pom.xml b/drools/pom.xml index c1e8b34b06..60df7157f2 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -5,10 +5,11 @@ drools - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + @@ -47,18 +48,13 @@ poi-ooxml ${apache-poi-version} - - org.springframework - spring-core - ${spring-core.version} - 4.4.6 7.4.1.Final 3.13 - 4.3.6.RELEASE + 4.3.6.RELEASE diff --git a/gson/pom.xml b/gson/pom.xml index 3e0bafee2c..912111374d 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -19,11 +20,6 @@ joda-time ${joda-time.version} - - com.google.guava - guava - ${guava.version} - commons-io commons-io diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml index d2ddcc3fac..b3deb305f2 100644 --- a/guava-modules/guava-18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -8,19 +8,11 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java - - - com.google.guava - guava - ${guava.version} - - - 18.0 diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml index 225dc9e9e3..9eb20d5bbe 100644 --- a/guava-modules/guava-19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -8,19 +8,11 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java - - - com.google.guava - guava - ${guava.version} - - - 19.0 diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index 42b66d84c8..7038810d24 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -7,18 +7,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java - - com.google.guava - guava - ${guava.version} - - org.jooq jool diff --git a/guava/pom.xml b/guava/pom.xml index 3ad3220f21..da880cc995 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -8,17 +8,13 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml index a63ccdee35..93ce207940 100644 --- a/guest/junit5-example/pom.xml +++ b/guest/junit5-example/pom.xml @@ -11,11 +11,6 @@ ../../ - - org.junit.jupiter - junit-jupiter-engine - 5.0.0-M4 - org.junit.jupiter junit-jupiter-params @@ -62,4 +57,8 @@ + + + + \ No newline at end of file diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index a3c714514e..da8f88ee22 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring diff --git a/hibernate5/README.md b/hibernate5/README.md index 4b7912056a..fb1319ed57 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -9,3 +9,4 @@ - [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor) - [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) - [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) diff --git a/httpclient/pom.xml b/httpclient/pom.xml index af50f38ebe..2f9b511133 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -8,17 +8,13 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-lang3 diff --git a/jackson/pom.xml b/jackson/pom.xml index fb2d48d4af..ea66f27833 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -8,18 +8,13 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java - - com.google.guava - guava - ${guava.version} - - commons-io commons-io diff --git a/jmh/pom.xml b/jmh/pom.xml index 2b82b7a9d5..60b59262b4 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -25,17 +26,6 @@ jmh-generator-annprocess ${openjdk.jmh.version} - - junit - junit - ${junit.version} - test - - - com.google.guava - guava - ${guava.version} - diff --git a/jsf/README.md b/jsf/README.md index ae92ffc42f..6e0891182d 100644 --- a/jsf/README.md +++ b/jsf/README.md @@ -2,3 +2,4 @@ - [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3) - [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language) - [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf) +- [Introduction to Primefaces](http://www.baeldung.com/jsf-primefaces) diff --git a/jsonb/pom.xml b/jsonb/pom.xml index f9db831fe3..c4ef1efed6 100644 --- a/jsonb/pom.xml +++ b/jsonb/pom.xml @@ -34,12 +34,6 @@ junit-jupiter-api ${junit.jupiter.version} - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - org.junit.platform junit-platform-surefire-provider diff --git a/libraries/README.md b/libraries/README.md index bf8c075663..f197ab1270 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -65,7 +65,7 @@ - [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries) +- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) - [Introduction to Smooks](http://www.baeldung.com/smooks) - [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) @@ -82,6 +82,8 @@ - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) +- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/logging-modules/README.md b/logging-modules/README.md index 6de71adb43..a589b1245c 100644 --- a/logging-modules/README.md +++ b/logging-modules/README.md @@ -5,3 +5,4 @@ - [Creating a Custom Logback Appender](http://www.baeldung.com/custom-logback-appender) - [Get Log Output in JSON Format](http://www.baeldung.com/java-log-json-output) +- [A Guide To Logback](http://www.baeldung.com/a-guide-to-logback) diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index 16eeff43cf..7628c708e9 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -9,28 +9,22 @@ tutorial on logging with MDC and NDC - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../../parent-spring + - - - org.springframework - spring-core - ${springframework.version} - org.springframework spring-web - ${springframework.version} + ${spring.version} org.springframework spring-webmvc - ${springframework.version} + ${spring.version} javax.servlet @@ -79,14 +73,14 @@ org.springframework spring-test - ${springframework.version} + ${spring.version} test - 4.3.4.RELEASE + 4.3.4.RELEASE 1.2.17 2.7 3.3.6 diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/pom.xml new file mode 100644 index 0000000000..74464a9631 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + + com.baeldung.log4j2 + modify-xml-configuration + 0.0.1-SNAPSHOT + modify-xml-configuration + http://maven.apache.org + + UTF-8 + + diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java new file mode 100644 index 0000000000..e92c66f168 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java @@ -0,0 +1,29 @@ +/** + This class demonstrates on modifying the loaded xml configuration by + extending XMLConfigurationFactory as defined in section 4.4 of + "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.log4j2.config; + +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.Order; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; + +@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY) +@Order(50) +public class CustomXMLConfigurationFactory extends XmlConfigurationFactory { + + @Override + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + return new MyXMLConfiguration(loggerContext, source); + } + + @Override + public String[] getSupportedTypes() { + return new String[] { ".xml", "*" }; + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java new file mode 100644 index 0000000000..45ee421316 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java @@ -0,0 +1,35 @@ +/** + This class demonstrates on overriding the configuration loaded through xml + as defined in section 4.4 of "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.log4j2.config; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.FileAppender; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.config.xml.XmlConfiguration; +import org.apache.logging.log4j.core.layout.PatternLayout; + +public class MyXMLConfiguration extends XmlConfiguration { + public MyXMLConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + super(loggerContext, source); + } + + @Override + protected void doConfigure() { + super.doConfigure(); + final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig("com"); + final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null); + Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config); + loggerConfig.addAppender(appender, Level.DEBUG, null); + addAppender(appender); + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..36823c8122 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java new file mode 100644 index 0000000000..993c0d0648 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java @@ -0,0 +1,23 @@ +package com.baeldung.log4j2.logtest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.plugins.util.PluginManager; +import org.junit.Test; + + +public class LogTest { + static{ + PluginManager.addPackage("com.baeldung.log4j2.config"); + } + + @Test + public void simpleProgrammaticConfiguration() { + Logger logger = LogManager.getLogger(); + LoggerContext ctx = (LoggerContext) LogManager.getContext(); + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/pom.xml new file mode 100644 index 0000000000..cd3aced397 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + pom + + simple-configuration + set-configuration-factory + simple-configurator + simple-configuration-xml + modify-xml-configuration + + + + junit + junit + 4.12 + test + + + org.apache.logging.log4j + log4j-core + 2.11.0 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.11.0 + + + diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml new file mode 100644 index 0000000000..f2a72563e9 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml @@ -0,0 +1,10 @@ + + 4.0.0 + + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + + set-configuration-factory + \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java new file mode 100644 index 0000000000..9c48702ba0 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java @@ -0,0 +1,88 @@ +/** + This class demonstrates how to build the components of + the configuration factory, as described in Section 3 of + "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.log4j2.config; + +import java.io.IOException; +import java.net.URI; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; +import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder; +import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; + +public class CustomConfigurationFactory extends ConfigurationFactory { + + static Configuration createConfiguration(final String name, ConfigurationBuilder builder) { + AppenderComponentBuilder console = builder.newAppender("Stdout", "Console"); + LayoutComponentBuilder layout = builder.newLayout("PatternLayout") + .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"); + console.add(layout); + FilterComponentBuilder filter = builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY); + filter.addAttribute("marker", "FLOW"); + console.add(filter); + builder.add(console); + ComponentBuilder triggeringPolicies = builder.newComponent("Policies") + .addComponent(builder.newComponent("CronTriggeringPolicy") + .addAttribute("schedule", "0 0 0 * * ?")) + .addComponent(builder.newComponent("SizeBasedTriggeringPolicy") + .addAttribute("size", "100M")); + AppenderComponentBuilder rollingFile = builder.newAppender("rolling", "RollingFile"); + rollingFile.addAttribute("fileName", "target/rolling.log"); + rollingFile.addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz"); + rollingFile.add(layout); + rollingFile.addComponent(triggeringPolicies); + builder.add(rollingFile); + AppenderComponentBuilder file = builder.newAppender("FileSystem", "File"); + file.addAttribute("fileName", "target/logging.log"); + file.add(layout); + builder.add(file); + LoggerComponentBuilder logger = builder.newLogger("com", Level.DEBUG); + logger.add(builder.newAppenderRef("Stdout")); + logger.add(builder.newAppenderRef("rolling")); + logger.add(builder.newAppenderRef("FileSystem")); + logger.addAttribute("additivity", false); + builder.add(logger); + RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.ERROR); + rootLogger.add(builder.newAppenderRef("Stdout")); + rootLogger.add(builder.newAppenderRef("rolling")); + rootLogger.add(builder.newAppenderRef("FileSystem")); + rootLogger.addAttribute("additivity", false); + builder.add(rootLogger); + try { + builder.writeXmlConfiguration(System.out); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return builder.build(); + } + + public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) { + ConfigurationBuilder builder = newConfigurationBuilder(); + return createConfiguration(name, builder); + } + + @Override + protected String[] getSupportedTypes() { + return new String[] { "*" }; + } + + @Override + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + return getConfiguration(loggerContext, source.toString(), null); + } + +} diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java new file mode 100644 index 0000000000..bf78a04dc4 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java @@ -0,0 +1,33 @@ +/** + This class invokes the configuration factory with static initialization, + as defined in section 4.1 of the "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.log4j2.logtest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import com.baeldung.log4j2.config.CustomConfigurationFactory; + +@RunWith(JUnit4.class) +public class LogTest { + static { + CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory(); + ConfigurationFactory.setConfigurationFactory(customConfigurationFactory); + } + + @Test + public void simpleProgrammaticConfiguration() { + Logger logger = LogManager.getLogger(); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml new file mode 100644 index 0000000000..de8c1ff70b --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + + simple-configuration-xml + simple-configuration-xml + http://maven.apache.org + + UTF-8 + + diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..4c49d85471 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java new file mode 100644 index 0000000000..f32e0796b6 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java @@ -0,0 +1,30 @@ +/** + This class loads the logging configuration from the xml defined in + src/main/resources and uses the same configuration generated through + programmatic configuration as defined in simple-configuration example. +**/ + +package com.baeldung.log4j2.logtest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + + +@RunWith(JUnit4.class) +public class LogTest { + + @Test + public void simpleProgrammaticConfiguration(){ + Logger logger = LogManager.getLogger(); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } + +} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml new file mode 100644 index 0000000000..0f9e5be3ff --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml @@ -0,0 +1,10 @@ + + 4.0.0 + + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + + simple-configuration + \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java b/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java new file mode 100644 index 0000000000..ca3cfa142d --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java @@ -0,0 +1,94 @@ +/** + This class demonstrates how to build the components of + the configuration factory, as described in Section 3 of + "Programmatic Configuration with Log4j 2" +**/ + +package com.baeldung.log4j2.config; + +import java.io.IOException; +import java.net.URI; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.Order; +import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; +import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder; +import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; +import org.apache.logging.log4j.core.config.plugins.Plugin; + +@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY) +@Order(50) +public class CustomConfigurationFactory extends ConfigurationFactory { + + static Configuration createConfiguration(final String name, ConfigurationBuilder builder) { + AppenderComponentBuilder console = builder.newAppender("Stdout", "Console"); + LayoutComponentBuilder layout = builder.newLayout("PatternLayout") + .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"); + console.add(layout); + FilterComponentBuilder filter = builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY); + filter.addAttribute("marker", "FLOW"); + console.add(filter); + builder.add(console); + ComponentBuilder triggeringPolicies = builder.newComponent("Policies") + .addComponent(builder.newComponent("CronTriggeringPolicy") + .addAttribute("schedule", "0 0 0 * * ?")) + .addComponent(builder.newComponent("SizeBasedTriggeringPolicy") + .addAttribute("size", "100M")); + AppenderComponentBuilder rollingFile = builder.newAppender("rolling", "RollingFile"); + rollingFile.addAttribute("fileName", "target/rolling.log"); + rollingFile.addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz"); + rollingFile.add(layout); + rollingFile.addComponent(triggeringPolicies); + builder.add(rollingFile); + AppenderComponentBuilder file = builder.newAppender("FileSystem", "File"); + file.addAttribute("fileName", "target/logging.log"); + file.add(layout); + builder.add(file); + LoggerComponentBuilder logger = builder.newLogger("com", Level.DEBUG); + logger.add(builder.newAppenderRef("Stdout")); + logger.add(builder.newAppenderRef("rolling")); + logger.add(builder.newAppenderRef("FileSystem")); + logger.addAttribute("additivity", false); + builder.add(logger); + RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.ERROR); + rootLogger.add(builder.newAppenderRef("Stdout")); + rootLogger.add(builder.newAppenderRef("rolling")); + // rootLogger.add(builder.newAppenderRef("syslogAppender")); + rootLogger.add(builder.newAppenderRef("FileSystem")); + rootLogger.addAttribute("additivity", false); + builder.add(rootLogger); + try { + builder.writeXmlConfiguration(System.out); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return builder.build(); + + } + + @Override + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + return getConfiguration(loggerContext, source.toString(), null); + } + + public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) { + ConfigurationBuilder builder = newConfigurationBuilder(); + return createConfiguration(name, builder); + } + + @Override + protected String[] getSupportedTypes() { + return new String[] { "*" }; + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java new file mode 100644 index 0000000000..5637a16508 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java @@ -0,0 +1,22 @@ +/** + This class invokes the configuration factory through the run time property, + as defined in section 4.2 of the "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.log4j2.logtest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.junit.Test; + +public class LogTest { + @Test + public void simpleProgrammaticConfiguration() { + Logger logger = LogManager.getLogger(); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml new file mode 100644 index 0000000000..4e7350f785 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml @@ -0,0 +1,10 @@ + + 4.0.0 + + com.baeldung.log4j2 + log4j2-programmatic-configuration + 0.0.1-SNAPSHOT + + simple-configurator + \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java b/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java new file mode 100644 index 0000000000..a5a10426ac --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java @@ -0,0 +1,40 @@ +/** + This class demonstrates how to use ConfigurationBuilderFactory directly, + as described in Section 3 of "Programmatic Configuration with Log4j 2" +**/ + +package com.baeldung.log4j2.configure; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.appender.ConsoleAppender; +import org.apache.logging.log4j.core.config.Configurator; +import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; +import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import com.baeldung.log4j2.logtest.LogPrinter; + +@RunWith(JUnit4.class) +public class LogTest { + @Test + public void simpleProgrammaticConfiguration() { + ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); + AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE") + .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); + console.add(builder.newLayout("PatternLayout") + .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); + builder.add(console); + builder.add(builder.newLogger("com", Level.DEBUG) + .add(builder.newAppenderRef("Stdout")) + .addAttribute("additivity", false)); + builder.add(builder.newRootLogger(Level.ERROR) + .add(builder.newAppenderRef("Stdout"))); + Configurator.initialize(builder.build()); + LogPrinter logPrinter = new LogPrinter(); + logPrinter.printlog(); + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java b/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java new file mode 100644 index 0000000000..d96808c105 --- /dev/null +++ b/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java @@ -0,0 +1,15 @@ +package com.baeldung.log4j2.logtest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + + +public class LogPrinter { + private Logger logger = LogManager.getLogger(); + + public void printlog() { + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } +} diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java new file mode 100644 index 0000000000..85201965dc --- /dev/null +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java @@ -0,0 +1,89 @@ +package com.baeldung.logback; + +import ch.qos.logback.classic.Level; +import org.junit.Test; + +import ch.qos.logback.classic.Logger; +import org.slf4j.LoggerFactory; + +public class LogbackTests { + + @Test + public void givenLogHierarchy_MessagesFiltered() { + + ch.qos.logback.classic.Logger parentLogger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + + parentLogger.setLevel(Level.INFO); + + Logger childlogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger("com.baeldung.logback.tests"); + + parentLogger.warn("This message is logged because WARN > INFO."); + + // This request is disabled, because DEBUG < INFO. + parentLogger.debug("This message is not logged because DEBUG < INFO."); + + childlogger.info("INFO == INFO"); + + childlogger.debug("DEBUG < INFO"); + + } + + @Test + public void givenRootLevel_MessagesFiltered() { + + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + + logger.debug("Hi there!"); + + Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + + logger.debug("This message is logged because DEBUG == DEBUG."); + + rootLogger.setLevel(Level.ERROR); + logger.warn("This message is not logged because WARN < ERROR."); + + logger.error("This is logged."); + + } + + @Test + public void givenParameters_ValuesLogged() { + + Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LogbackTests.class); + + String message = "This is a String"; + Integer zero = 0; + + try { + logger.debug("Logging message: {}", message); + logger.debug("Going to divide {} by {}", 42, zero); + int result = 42 / zero; + } catch (Exception e) { + logger.error("Error dividing {} by {} ", 42, zero, e); + } + } + + @Test + public void givenConfig_MessageFiltered() { + + Logger foobar = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.foobar"); + Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback"); + Logger testslogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.logback.tests"); + + foobar.debug("This is logged from foobar"); + logger.debug("This is not logged from logger"); + logger.info("This is logged from logger"); + testslogger.info("This is not logged from tests"); + testslogger.warn("This is logged from tests"); + + + } + + + + + + +} diff --git a/logging-modules/logback/src/test/resources/logback-guide.xml b/logging-modules/logback/src/test/resources/logback-guide.xml new file mode 100644 index 0000000000..8331f1cb93 --- /dev/null +++ b/logging-modules/logback/src/test/resources/logback-guide.xml @@ -0,0 +1,32 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + tests.log + true + + true + + + %-4relative [%thread] %-5level %logger{35} - %msg%n + + + + + + + + + + + + + \ No newline at end of file diff --git a/parent-boot-2/README.md b/parent-boot-2/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-boot-2/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml new file mode 100644 index 0000000000..a9c54dece9 --- /dev/null +++ b/parent-boot-2/pom.xml @@ -0,0 +1,120 @@ + + 4.0.0 + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + pom + Parent Boot 2 + Parent for all spring boot 2 modules + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + + junit + junit + test + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*LiveTest.java + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + **/AutoconfigurationTest.java + **/*UnitTest.java + + + **/*IntegrationTest.java + */EthControllerTestOne.java + **/*IntTest.java + **/*EntryPointsTest.java + + + + + + + json + + + + + + + + + + UTF-8 + UTF-8 + 1.8 + 3.1.0 + + 1.8 + 1.8 + + + \ No newline at end of file diff --git a/parent-java/README.md b/parent-java/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-java/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-java/pom.xml b/parent-java/pom.xml new file mode 100644 index 0000000000..40df31d1c7 --- /dev/null +++ b/parent-java/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + com.baeldung + parent-java + 0.0.1-SNAPSHOT + pom + parent-java + Parent for all java modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.google.guava + guava + ${guava.version} + + + + + 22.0 + + + \ No newline at end of file diff --git a/parent-spring/README.md b/parent-spring/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-spring/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-spring/pom.xml b/parent-spring/pom.xml new file mode 100644 index 0000000000..547c43dc27 --- /dev/null +++ b/parent-spring/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + pom + parent-spring + Parent for all spring core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + 4.3.6.RELEASE + 5.0.2 + + + \ No newline at end of file diff --git a/patterns/behavioral-patterns/pom.xml b/patterns/behavioral-patterns/pom.xml index 03b138dfc4..435f07aa98 100644 --- a/patterns/behavioral-patterns/pom.xml +++ b/patterns/behavioral-patterns/pom.xml @@ -19,10 +19,22 @@ 4.12 test + + org.hamcrest + hamcrest-core + 1.3 + test + + + org.assertj + assertj-core + 3.8.0 + test + UTF-8 1.8 1.8 - + \ No newline at end of file diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/client/TextFileApplication.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/client/TextFileApplication.java new file mode 100644 index 0000000000..30dcf08e89 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/client/TextFileApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.pattern.command.client; + +import com.baeldung.pattern.command.command.OpenTextFileOperation; +import com.baeldung.pattern.command.command.SaveTextFileOperation; +import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; +import com.baeldung.pattern.command.receiver.TextFile; + +public class TextFileApplication { + + public static void main(String[] args) { + + TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt")); + TextFileOperation saveTextFileOperation = new SaveTextFileOperation(new TextFile("file2.txt")); + TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor(); + System.out.println(textFileOperationExecutor.executeOperation(openTextFileOperation)); + System.out.println(textFileOperationExecutor.executeOperation(saveTextFileOperation)); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/OpenTextFileOperation.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/OpenTextFileOperation.java new file mode 100644 index 0000000000..c90a162b88 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/OpenTextFileOperation.java @@ -0,0 +1,17 @@ +package com.baeldung.pattern.command.command; + +import com.baeldung.pattern.command.receiver.TextFile; + +public class OpenTextFileOperation implements TextFileOperation { + + private final TextFile textFile; + + public OpenTextFileOperation(TextFile textFile) { + this.textFile = textFile; + } + + @Override + public String execute() { + return textFile.open(); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/SaveTextFileOperation.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/SaveTextFileOperation.java new file mode 100644 index 0000000000..b908e2c44c --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/SaveTextFileOperation.java @@ -0,0 +1,17 @@ +package com.baeldung.pattern.command.command; + +import com.baeldung.pattern.command.receiver.TextFile; + +public class SaveTextFileOperation implements TextFileOperation { + + private final TextFile textFile; + + public SaveTextFileOperation(TextFile textFile) { + this.textFile = textFile; + } + + @Override + public String execute() { + return textFile.save(); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/TextFileOperation.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/TextFileOperation.java new file mode 100644 index 0000000000..506bb23d99 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/command/TextFileOperation.java @@ -0,0 +1,8 @@ +package com.baeldung.pattern.command.command; + +@FunctionalInterface +public interface TextFileOperation { + + String execute(); + +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/invoker/TextFileOperationExecutor.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/invoker/TextFileOperationExecutor.java new file mode 100644 index 0000000000..bd2213706e --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/invoker/TextFileOperationExecutor.java @@ -0,0 +1,15 @@ +package com.baeldung.pattern.command.invoker; + +import com.baeldung.pattern.command.command.TextFileOperation; +import java.util.ArrayList; +import java.util.List; + +public class TextFileOperationExecutor { + + private final List textFileOperations = new ArrayList<>(); + + public String executeOperation(TextFileOperation textFileOperation) { + textFileOperations.add(textFileOperation); + return textFileOperation.execute(); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/receiver/TextFile.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/receiver/TextFile.java new file mode 100644 index 0000000000..c0b2d3c41e --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/command/receiver/TextFile.java @@ -0,0 +1,34 @@ +package com.baeldung.pattern.command.receiver; + +public class TextFile { + + private final String name; + + public TextFile(String name) { + this.name = name; + } + + public String open() { + return "Opening file " + name; + } + + public String read() { + return "Reading file " + name; + } + + public String write() { + return "Writing to file " + name; + } + + public String save() { + return "Saving file " + name; + } + + public String copy() { + return "Copying file " + name; + } + + public String paste() { + return "Pasting file " + name; + } +} diff --git a/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/OpenTextFileOperationUnitTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/OpenTextFileOperationUnitTest.java new file mode 100644 index 0000000000..1c72bfdd2f --- /dev/null +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/OpenTextFileOperationUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.pattern.command.test; + +import com.baeldung.pattern.command.command.OpenTextFileOperation; +import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.pattern.command.receiver.TextFile; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class OpenTextFileOperationUnitTest { + + @Test + public void givenOpenTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() { + TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt")); + assertThat(openTextFileOperation.execute()).isEqualTo("Opening file file1.txt"); + } +} diff --git a/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/SaveTextFileOperationUnitTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/SaveTextFileOperationUnitTest.java new file mode 100644 index 0000000000..a7bc1f3025 --- /dev/null +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/SaveTextFileOperationUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.pattern.command.test; + +import com.baeldung.pattern.command.command.SaveTextFileOperation; +import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.pattern.command.receiver.TextFile; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class SaveTextFileOperationUnitTest { + + @Test + public void givenSaveTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() { + TextFileOperation openTextFileOperation = new SaveTextFileOperation(new TextFile("file1.txt")); + assertThat(openTextFileOperation.execute()).isEqualTo("Saving file file1.txt"); + } +} diff --git a/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileOperationExecutorUnitTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileOperationExecutorUnitTest.java new file mode 100644 index 0000000000..efafa0d8a2 --- /dev/null +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileOperationExecutorUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.pattern.command.test; + +import com.baeldung.pattern.command.command.OpenTextFileOperation; +import com.baeldung.pattern.command.command.SaveTextFileOperation; +import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; +import com.baeldung.pattern.command.receiver.TextFile; +import java.util.function.Function; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; +import org.junit.BeforeClass; + +public class TextFileOperationExecutorUnitTest { + + private static TextFileOperationExecutor textFileOperationExecutor; + + + @BeforeClass + public static void setUpTextFileOperationExecutor() { + textFileOperationExecutor = new TextFileOperationExecutor(); + } + + @Test + public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithOpenTextOperation_thenOneAssertion() { + TextFileOperation textFileOperation = new OpenTextFileOperation(new TextFile("file1.txt")); + assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Opening file file1.txt"); + } + + @Test + public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithSaveTextOperation_thenOneAssertion() { + TextFileOperation textFileOperation = new SaveTextFileOperation(new TextFile("file1.txt")); + assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Saving file file1.txt"); + } + + @Test + public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenLambda_thenOneAssertion() { + assertThat(textFileOperationExecutor.executeOperation(() -> {return "Opening file file1.txt";})).isEqualTo("Opening file file1.txt"); + } + + @Test + public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveLambda_thenOneAssertion() { + assertThat(textFileOperationExecutor.executeOperation(() -> {return "Saving file file1.txt";})).isEqualTo("Saving file file1.txt"); + } + + @Test + public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenMethodReferenceOfExistingObject_thenOneAssertion() { + TextFile textFile = new TextFile("file1.txt"); + assertThat(textFileOperationExecutor.executeOperation(textFile::open)).isEqualTo("Opening file file1.txt"); + } + + @Test + public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveMethodReferenceOfExistingObject_thenOneAssertion() { + TextFile textFile = new TextFile("file1.txt"); + assertThat(textFileOperationExecutor.executeOperation(textFile::save)).isEqualTo("Saving file file1.txt"); + } + + @Test + public void givenOpenTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() { + Function executeMethodReference = OpenTextFileOperation::execute; + assertThat(executeMethodReference.apply(new OpenTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Opening file file1.txt"); + } + + @Test + public void givenSaveTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() { + Function executeMethodReference = SaveTextFileOperation::execute; + assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt"); + } +} diff --git a/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileUnitTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileUnitTest.java new file mode 100644 index 0000000000..32b83897c9 --- /dev/null +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/command/test/TextFileUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.pattern.command.test; + +import com.baeldung.pattern.command.receiver.TextFile; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; +import org.junit.BeforeClass; + +public class TextFileUnitTest { + + private static TextFile textFile; + + + @BeforeClass + public static void setUpTextFileInstance() { + textFile = new TextFile("file1.txt"); + } + + @Test + public void givenTextFileInstance_whenCalledopenMethod_thenOneAssertion() { + assertThat(textFile.open()).isEqualTo("Opening file file1.txt"); + } + + @Test + public void givenTextFileInstance_whenCalledwriteMethod_thenOneAssertion() { + assertThat(textFile.write()).isEqualTo("Writing to file file1.txt"); + } + + @Test + public void givenTextFileInstance_whenCalledsaveMethod_thenOneAssertion() { + assertThat(textFile.save()).isEqualTo("Saving file file1.txt"); + } + + @Test + public void givenTextFileInstance_whenCalledcopyMethod_thenOneAssertion() { + assertThat(textFile.copy()).isEqualTo("Copying file file1.txt"); + } + + @Test + public void givenTextFileInstance_whenCalledpasteMethod_thenOneAssertion() { + assertThat(textFile.paste()).isEqualTo("Pasting file file1.txt"); + } +} diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml new file mode 100644 index 0000000000..3f25796516 --- /dev/null +++ b/performance-tests/pom.xml @@ -0,0 +1,79 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + performancetests + + + + ma.glasnost.orika + orika-core + 1.5.2 + + + net.sf.dozer + dozer + 5.5.1 + + + io.craftsman + dozer-jdk8-support + 1.0.2 + + + org.mapstruct + mapstruct-jdk8 + 1.2.0.Final + + + org.modelmapper + modelmapper + 1.1.0 + + + com.googlecode.jmapper-framework + jmapper-core + 1.6.0.1 + + + org.openjdk.jmh + jmh-core + 1.20 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.20 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + org.mapstruct + mapstruct-processor + 1.2.0.Final + + + + + + + + + \ No newline at end of file diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/Converter.java b/performance-tests/src/main/java/com/baeldung/performancetests/Converter.java new file mode 100644 index 0000000000..097600849b --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/Converter.java @@ -0,0 +1,11 @@ +package com.baeldung.performancetests; + +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; + +public interface Converter { + Order convert(SourceOrder sourceOrder); + DestinationCode convert(SourceCode sourceCode); +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/dozer/DozerConverter.java b/performance-tests/src/main/java/com/baeldung/performancetests/dozer/DozerConverter.java new file mode 100644 index 0000000000..710145ec58 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/dozer/DozerConverter.java @@ -0,0 +1,29 @@ +package com.baeldung.performancetests.dozer; + +import com.baeldung.performancetests.Converter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; +import org.dozer.DozerBeanMapper; +import org.dozer.Mapper; + + public class DozerConverter implements Converter { + private final Mapper mapper; + + public DozerConverter() { + DozerBeanMapper mapper = new DozerBeanMapper(); + mapper.addMapping(DozerConverter.class.getResourceAsStream("/dozer-mapping.xml")); + this.mapper = mapper; + } + + @Override + public Order convert(SourceOrder sourceOrder) { + return mapper.map(sourceOrder,Order.class); + } + + @Override + public DestinationCode convert(SourceCode sourceCode) { + return mapper.map(sourceCode, DestinationCode.class); + } + } diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/jmapper/JMapperConverter.java b/performance-tests/src/main/java/com/baeldung/performancetests/jmapper/JMapperConverter.java new file mode 100644 index 0000000000..b61cfbb771 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/jmapper/JMapperConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.performancetests.jmapper; + +import com.baeldung.performancetests.Converter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; +import com.googlecode.jmapper.JMapper; +import com.googlecode.jmapper.api.JMapperAPI; + +public class JMapperConverter implements Converter { + JMapper realLifeMapper; + JMapper simpleMapper; + public JMapperConverter() { + JMapperAPI api = new JMapperAPI().add(JMapperAPI.mappedClass(Order.class)); + realLifeMapper = new JMapper(Order.class, SourceOrder.class, api); + JMapperAPI simpleApi = new JMapperAPI().add(JMapperAPI.mappedClass(DestinationCode.class)); + simpleMapper = new JMapper(DestinationCode.class, SourceCode.class, simpleApi); + } + + @Override + public Order convert(SourceOrder sourceOrder) { + return (Order) realLifeMapper.getDestination(sourceOrder); + } + + @Override + public DestinationCode convert(SourceCode sourceCode) { + return (DestinationCode) simpleMapper.getDestination(sourceCode); + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/mapstruct/MapStructConverter.java b/performance-tests/src/main/java/com/baeldung/performancetests/mapstruct/MapStructConverter.java new file mode 100644 index 0000000000..27ec6e6c83 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/mapstruct/MapStructConverter.java @@ -0,0 +1,22 @@ +package com.baeldung.performancetests.mapstruct; + +import com.baeldung.performancetests.Converter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface MapStructConverter extends Converter { + MapStructConverter MAPPER = Mappers.getMapper(MapStructConverter.class); + + @Mapping(source = "status", target = "orderStatus") + @Override + Order convert(SourceOrder sourceOrder); + + @Override + DestinationCode convert(SourceCode sourceCode); +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/AccountStatus.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/AccountStatus.java new file mode 100644 index 0000000000..c435a73b56 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/AccountStatus.java @@ -0,0 +1,5 @@ +package com.baeldung.performancetests.model.destination; + +public enum AccountStatus { + ACTIVE, NOT_ACTIVE, BANNED +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Address.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Address.java new file mode 100644 index 0000000000..9107f47455 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Address.java @@ -0,0 +1,83 @@ +package com.baeldung.performancetests.model.destination; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.util.Objects; + +@JGlobalMap +public class Address { + private String street; + private String city; + private String postalCode; + + public Address() { + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if(o.getClass() == com.baeldung.performancetests.model.source.Address.class) { + com.baeldung.performancetests.model.source.Address address = + (com.baeldung.performancetests.model.source.Address) o; + return Objects.equals(street, address.getStreet()) && + Objects.equals(city, address.getCity()) && + Objects.equals(postalCode, address.getPostalCode()) && + Objects.equals(country, address.getCountry()); + } + if(o.getClass() != getClass()) return false; + Address address = (Address) o; + return Objects.equals(street, address.street) && + Objects.equals(city, address.city) && + Objects.equals(postalCode, address.postalCode) && + Objects.equals(country, address.country); + } + + @Override + public int hashCode() { + + return Objects.hash(street, city, postalCode, country); + } + + private String country; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Address(String street, String city, String postalCode, String country) { + + this.street = street; + this.city = city; + this.postalCode = postalCode; + this.country = country; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DeliveryData.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DeliveryData.java new file mode 100644 index 0000000000..1d9bde1088 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DeliveryData.java @@ -0,0 +1,83 @@ +package com.baeldung.performancetests.model.destination; + +import com.googlecode.jmapper.annotations.JGlobalMap; +import com.googlecode.jmapper.annotations.JMapAccessor; + +import java.util.Objects; + +@JGlobalMap +public class DeliveryData { + private Address deliveryAddress; + @JMapAccessor(get = "isPrePaid", set = "setPrePaid") + private boolean isPrePaid; + private String trackingCode; + private int expectedDeliveryTimeInDays; + + public DeliveryData() { + } + + public Address getDeliveryAddress() { + return deliveryAddress; + } + + public void setDeliveryAddress(Address deliveryAddress) { + this.deliveryAddress = deliveryAddress; + } + + public boolean isPrePaid() { + return isPrePaid; + } + + public void setPrePaid(boolean prePaid) { + isPrePaid = prePaid; + } + + public String getTrackingCode() { + return trackingCode; + } + + public void setTrackingCode(String trackingCode) { + this.trackingCode = trackingCode; + } + + public int getExpectedDeliveryTimeInDays() { + return expectedDeliveryTimeInDays; + } + + public void setExpectedDeliveryTimeInDays(int expectedDeliveryTimeInDays) { + this.expectedDeliveryTimeInDays = expectedDeliveryTimeInDays; + } + + public DeliveryData(Address deliveryAddress, boolean isPrePaid, String trackingCode, int expectedDeliveryTimeInDays) { + this.deliveryAddress = deliveryAddress; + this.isPrePaid = isPrePaid; + this.trackingCode = trackingCode; + this.expectedDeliveryTimeInDays = expectedDeliveryTimeInDays; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if(o.getClass() == com.baeldung.performancetests.model.source.DeliveryData.class) { + com.baeldung.performancetests.model.source.DeliveryData deliveryData = + (com.baeldung.performancetests.model.source.DeliveryData) o; + return isPrePaid == deliveryData.isPrePaid() && + expectedDeliveryTimeInDays == deliveryData.getExpectedDeliveryTimeInDays() && + Objects.equals(deliveryAddress, deliveryData.getDeliveryAddress()) && + Objects.equals(trackingCode, deliveryData.getTrackingCode()); + } + if (o.getClass() != getClass()) return false; + DeliveryData that = (DeliveryData) o; + return isPrePaid == that.isPrePaid && + expectedDeliveryTimeInDays == that.expectedDeliveryTimeInDays && + Objects.equals(deliveryAddress, that.deliveryAddress) && + Objects.equals(trackingCode, that.trackingCode); + } + + @Override + public int hashCode() { + + return Objects.hash(deliveryAddress, isPrePaid, trackingCode, expectedDeliveryTimeInDays); + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DestinationCode.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DestinationCode.java new file mode 100644 index 0000000000..d0a7985db8 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/DestinationCode.java @@ -0,0 +1,23 @@ +package com.baeldung.performancetests.model.destination; + +import com.googlecode.jmapper.annotations.JMap; + +public class DestinationCode { + @JMap + String code; + + public DestinationCode(String code) { + this.code = code; + } + + public DestinationCode() { + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Discount.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Discount.java new file mode 100644 index 0000000000..920cc71a7e --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Discount.java @@ -0,0 +1,70 @@ +package com.baeldung.performancetests.model.destination; + +import com.google.common.base.Objects; +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.math.BigDecimal; + +@JGlobalMap +public class Discount { + private String startTime; + private String endTime; + private BigDecimal discountPrice; + + public Discount() { + } + + public String getStartTime() { + return startTime; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if (o.getClass() == com.baeldung.performancetests.model.source.Discount.class) { + com.baeldung.performancetests.model.source.Discount discount = + (com.baeldung.performancetests.model.source.Discount) o; + return Objects.equal(startTime, discount.getStartTime()) && + Objects.equal(endTime, discount.getEndTime()) && + Objects.equal(discountPrice, discount.getDiscountPrice()); + } + if(o.getClass() != getClass()) return false; + Discount discount = (Discount) o; + return Objects.equal(startTime, discount.startTime) && + Objects.equal(endTime, discount.endTime) && + Objects.equal(discountPrice, discount.discountPrice); + } + + @Override + public int hashCode() { + return Objects.hashCode(startTime, endTime, discountPrice); + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + public BigDecimal getDiscountPrice() { + return discountPrice; + } + + public void setDiscountPrice(BigDecimal discountPrice) { + this.discountPrice = discountPrice; + } + + public Discount(String startTime, String endTime, BigDecimal discountPrice) { + + this.startTime = startTime; + this.endTime = endTime; + this.discountPrice = discountPrice; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Order.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Order.java new file mode 100644 index 0000000000..cbce84efc4 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Order.java @@ -0,0 +1,210 @@ +package com.baeldung.performancetests.model.destination; + +import com.baeldung.performancetests.model.source.SourceOrder; +import com.google.common.base.Objects; +import com.googlecode.jmapper.annotations.JMap; +import com.googlecode.jmapper.annotations.JMapConversion; + +import java.util.List; +public class Order { + @JMap + private User orderingUser; + @JMap + private List orderedProducts; + @JMap("status") + private OrderStatus orderStatus; + @JMap + private String orderDate; + @JMap + private String orderFinishDate; + @JMap + private PaymentType paymentType; + @JMap + private Discount discount; + @JMap + private int orderId; + @JMap + private DeliveryData deliveryData; + @JMap + private Shop offeringShop; + + public Order() { + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if (o.getClass() == SourceOrder.class) { + SourceOrder order = + (SourceOrder) o; + return Objects.equal(orderingUser, order.getOrderingUser()) && + Objects.equal(orderedProducts, order.getOrderedProducts()) && + orderStatus.ordinal() == order.getStatus().ordinal() && + Objects.equal(orderDate, order.getOrderDate()) && + Objects.equal(orderFinishDate, order.getOrderFinishDate()) && + paymentType.ordinal() == order.getPaymentType().ordinal() && + Objects.equal(discount, order.getDiscount()) && + Objects.equal(deliveryData, order.getDeliveryData()); + } + if (o.getClass() != getClass()) return false; + Order order = (Order) o; + return Objects.equal(orderingUser, order.orderingUser) && + Objects.equal(orderedProducts, order.orderedProducts) && + orderStatus == order.orderStatus && + Objects.equal(orderDate, order.orderDate) && + Objects.equal(orderFinishDate, order.orderFinishDate) && + paymentType == order.paymentType && + Objects.equal(discount, order.discount) && + Objects.equal(deliveryData, order.deliveryData); + } + + @Override + public int hashCode() { + return Objects.hashCode(orderingUser, orderedProducts, orderStatus, orderDate, orderFinishDate, paymentType, discount, deliveryData); + } + + public User getOrderingUser() { + return orderingUser; + } + + public void setOrderingUser(User orderingUser) { + this.orderingUser = orderingUser; + } + + public List getOrderedProducts() { + return orderedProducts; + } + + public void setOrderedProducts(List orderedProducts) { + this.orderedProducts = orderedProducts; + } + + public OrderStatus getOrderStatus() { + return orderStatus; + } + + public void setOrderStatus(OrderStatus status) { + this.orderStatus = status; + } + + public String getOrderDate() { + return orderDate; + } + + public void setOrderDate(String orderDate) { + this.orderDate = orderDate; + } + + public String getOrderFinishDate() { + return orderFinishDate; + } + + public void setOrderFinishDate(String orderFinishDate) { + this.orderFinishDate = orderFinishDate; + } + + public PaymentType getPaymentType() { + return paymentType; + } + + public void setPaymentType(PaymentType paymentType) { + this.paymentType = paymentType; + } + + public Discount getDiscount() { + return discount; + } + + public void setDiscount(Discount discount) { + this.discount = discount; + } + + public DeliveryData getDeliveryData() { + return deliveryData; + } + + public void setDeliveryData(DeliveryData deliveryData) { + this.deliveryData = deliveryData; + } + + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public Order(User orderingUser, List orderedProducts, OrderStatus orderStatus, String orderDate, String orderFinishDate, PaymentType paymentType, Discount discount, int orderId, DeliveryData deliveryData, Shop offeringShop) { + + this.orderingUser = orderingUser; + this.orderedProducts = orderedProducts; + this.orderStatus = orderStatus; + this.orderDate = orderDate; + this.orderFinishDate = orderFinishDate; + this.paymentType = paymentType; + this.discount = discount; + this.orderId = orderId; + this.deliveryData = deliveryData; + this.offeringShop = offeringShop; + } + + public Shop getOfferingShop() { + return offeringShop; + } + + public void setOfferingShop(Shop offeringShop) { + this.offeringShop = offeringShop; + } + + + + @JMapConversion(from = "status", to = "orderStatus") + public OrderStatus conversion(com.baeldung.performancetests.model.source.OrderStatus status) { + OrderStatus orderStatus = null; + switch(status) { + case CREATED: + orderStatus = OrderStatus.CREATED; + break; + case FINISHED: + orderStatus = OrderStatus.FINISHED; + break; + + case CONFIRMED: + orderStatus = OrderStatus.CONFIRMED; + break; + + case COLLECTING: + orderStatus = OrderStatus.COLLECTING; + break; + + case IN_TRANSPORT: + orderStatus = OrderStatus.IN_TRANSPORT; + break; + } + return orderStatus; + } + + @JMapConversion(from = "paymentType", to = "paymentType") + public PaymentType conversion(com.baeldung.performancetests.model.source.PaymentType type) { + PaymentType paymentType = null; + switch(type) { + case CARD: + paymentType = PaymentType.CARD; + break; + + case CASH: + paymentType = PaymentType.CASH; + break; + + case TRANSFER: + paymentType = PaymentType.TRANSFER; + break; + } + return paymentType; + } + + +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/OrderStatus.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/OrderStatus.java new file mode 100644 index 0000000000..48118201e1 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/OrderStatus.java @@ -0,0 +1,5 @@ +package com.baeldung.performancetests.model.destination; + +public enum OrderStatus { + CREATED, CONFIRMED, COLLECTING, IN_TRANSPORT, FINISHED +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/PaymentType.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/PaymentType.java new file mode 100644 index 0000000000..441e275b18 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/PaymentType.java @@ -0,0 +1,5 @@ +package com.baeldung.performancetests.model.destination; + +public enum PaymentType { + CASH, CARD, TRANSFER +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Product.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Product.java new file mode 100644 index 0000000000..bc1e95e2c0 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Product.java @@ -0,0 +1,107 @@ +package com.baeldung.performancetests.model.destination; + +import com.google.common.base.Objects; +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.math.BigDecimal; + +@JGlobalMap +public class Product { + private BigDecimal price; + private int quantity; + + public Product() { + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isAvailable() { + return available; + } + + public void setAvailable(boolean available) { + this.available = available; + } + + public RefundPolicy getRefundPolicy() { + return refundPolicy; + } + + public void setRefundPolicy(RefundPolicy refundPolicy) { + this.refundPolicy = refundPolicy; + } + + private String name; + + public Product(BigDecimal price, int quantity, String name, String description, boolean available, RefundPolicy refundPolicy) { + this.price = price; + this.quantity = quantity; + this.name = name; + this.description = description; + this.available = available; + this.refundPolicy = refundPolicy; + } + + String description; + boolean available; + private RefundPolicy refundPolicy; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if (o.getClass() == com.baeldung.performancetests.model.source.Product.class) { + com.baeldung.performancetests.model.source.Product product = + (com.baeldung.performancetests.model.source.Product) o; + return quantity == product.getQuantity() && + available == product.isAvailable() && + Objects.equal(price, product.getPrice()) && + Objects.equal(name, product.getName()) && + Objects.equal(description, product.getDescription()) && + Objects.equal(refundPolicy, product.getRefundPolicy()); + } + if(o.getClass() != getClass()) return false; + Product product = (Product) o; + return quantity == product.quantity && + available == product.available && + Objects.equal(price, product.price) && + Objects.equal(name, product.name) && + Objects.equal(description, product.description) && + Objects.equal(refundPolicy, product.refundPolicy); + } + + @Override + public int hashCode() { + return Objects.hashCode(price, quantity, name, description, available, refundPolicy); + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/RefundPolicy.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/RefundPolicy.java new file mode 100644 index 0000000000..523957596c --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/RefundPolicy.java @@ -0,0 +1,72 @@ +package com.baeldung.performancetests.model.destination; + +import com.google.common.base.Objects; +import com.googlecode.jmapper.annotations.JGlobalMap; +import com.googlecode.jmapper.annotations.JMapAccessor; + +import java.util.List; + +@JGlobalMap +public class RefundPolicy { + @JMapAccessor(get = "isRefundable", set = "setRefundable") + private boolean isRefundable; + private int refundTimeInDays; + + public RefundPolicy() { + } + + public boolean isRefundable() { + return isRefundable; + } + + public void setRefundable(boolean refundable) { + isRefundable = refundable; + } + + public int getRefundTimeInDays() { + return refundTimeInDays; + } + + public void setRefundTimeInDays(int refundTimeInDays) { + this.refundTimeInDays = refundTimeInDays; + } + + public List getNotes() { + return notes; + } + + public void setNotes(List notes) { + this.notes = notes; + } + + public RefundPolicy(boolean isRefundable, int refundTimeInDays, List notes) { + + this.isRefundable = isRefundable; + this.refundTimeInDays = refundTimeInDays; + this.notes = notes; + } + + private List notes; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if (o.getClass() == com.baeldung.performancetests.model.source.RefundPolicy.class) { + com.baeldung.performancetests.model.source.RefundPolicy that = (com.baeldung.performancetests.model.source.RefundPolicy) o; + return isRefundable == that.isRefundable() && + refundTimeInDays == that.getRefundTimeInDays() && + Objects.equal(notes, that.getNotes()); + } + if (o.getClass() != getClass()) return false; + RefundPolicy that = (RefundPolicy) o; + return isRefundable == that.isRefundable && + refundTimeInDays == that.refundTimeInDays && + Objects.equal(notes, that.notes); + } + + @Override + public int hashCode() { + return Objects.hashCode(isRefundable, refundTimeInDays, notes); + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Review.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Review.java new file mode 100644 index 0000000000..d1794d4913 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Review.java @@ -0,0 +1,67 @@ +package com.baeldung.performancetests.model.destination; + +import com.baeldung.performancetests.model.source.User; +import com.googlecode.jmapper.annotations.JGlobalMap; + +@JGlobalMap +public class Review { + + int shippingGrade; + int pricingGrade; + int serviceGrade; + User reviewingUser; + String note; + + public int getShippingGrade() { + return shippingGrade; + } + + public void setShippingGrade(int shippingGrade) { + this.shippingGrade = shippingGrade; + } + + public int getPricingGrade() { + return pricingGrade; + } + + public void setPricingGrade(int pricingGrade) { + this.pricingGrade = pricingGrade; + } + + public int getServiceGrade() { + return serviceGrade; + } + + public void setServiceGrade(int serviceGrade) { + this.serviceGrade = serviceGrade; + } + + public User getReviewingUser() { + return reviewingUser; + } + + public void setReviewingUser(User reviewingUser) { + this.reviewingUser = reviewingUser; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public Review() { + + } + + public Review(int shippingGrade, int pricingGrade, int serviceGrade, User reviewingUser, String note) { + + this.shippingGrade = shippingGrade; + this.pricingGrade = pricingGrade; + this.serviceGrade = serviceGrade; + this.reviewingUser = reviewingUser; + this.note = note; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Shop.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Shop.java new file mode 100644 index 0000000000..75f37b8bba --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/Shop.java @@ -0,0 +1,57 @@ +package com.baeldung.performancetests.model.destination; + +import com.baeldung.performancetests.model.source.Address; +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.util.List; +@JGlobalMap +public class Shop { + + private String shopName; + private Address shopAddres; + private String shopUrl; + private List reviews; + + public String getShopName() { + return shopName; + } + + public void setShopName(String shopName) { + this.shopName = shopName; + } + + public Address getShopAddres() { + return shopAddres; + } + + public void setShopAddres(Address shopAddres) { + this.shopAddres = shopAddres; + } + + public String getShopUrl() { + return shopUrl; + } + + public void setShopUrl(String shopUrl) { + this.shopUrl = shopUrl; + } + + public Shop() { + } + + public List getReviews() { + return reviews; + } + + public void setReviews(List reviews) { + this.reviews = reviews; + } + + public Shop(String shopName, Address shopAddres, String shopUrl, List reviews) { + + this.shopName = shopName; + this.shopAddres = shopAddres; + this.shopUrl = shopUrl; + this.reviews = reviews; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/User.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/User.java new file mode 100644 index 0000000000..6f604f64b3 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/destination/User.java @@ -0,0 +1,87 @@ +package com.baeldung.performancetests.model.destination; + +import com.google.common.base.Objects; +import com.googlecode.jmapper.annotations.JGlobalMap; +import com.googlecode.jmapper.annotations.JMapConversion; + +@JGlobalMap +public class User { + private String username; + private String email; + private AccountStatus userAccountStatus; + + public User(String username, String email, AccountStatus userAccountStatus) { + this.username = username; + this.email = email; + this.userAccountStatus = userAccountStatus; + } + + public User() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public AccountStatus getUserAccountStatus() { + return userAccountStatus; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null) return false; + if (o.getClass() == com.baeldung.performancetests.model.source.User.class) { + com.baeldung.performancetests.model.source.User user = + (com.baeldung.performancetests.model.source.User) o; + return Objects.equal(username, user.getUsername()) && + Objects.equal(email, user.getEmail()) && + userAccountStatus.ordinal() == user.getUserAccountStatus().ordinal(); + } + if (o.getClass() != getClass()) return false; + User user = (User) o; + return Objects.equal(username, user.username) && + Objects.equal(email, user.email) && + userAccountStatus == user.userAccountStatus; + } + + @Override + public int hashCode() { + return Objects.hashCode(username, email, userAccountStatus); + } + + public void setUserAccountStatus(AccountStatus userAccountStatus) { + this.userAccountStatus = userAccountStatus; + } + + + @JMapConversion(from = "userAccountStatus", to = "userAccountStatus") + public AccountStatus conversion(com.baeldung.performancetests.model.source.AccountStatus status) { + AccountStatus accountStatus = null; + switch(status) { + case ACTIVE: + accountStatus = AccountStatus.ACTIVE; + break; + case NOT_ACTIVE: + accountStatus = AccountStatus.NOT_ACTIVE; + break; + + case BANNED: + accountStatus = AccountStatus.BANNED; + break; + } + return accountStatus; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/AccountStatus.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/AccountStatus.java new file mode 100644 index 0000000000..e3e7d7964c --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/AccountStatus.java @@ -0,0 +1,7 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +public enum AccountStatus { + ACTIVE, NOT_ACTIVE, BANNED +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Address.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Address.java new file mode 100644 index 0000000000..2818fa0065 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Address.java @@ -0,0 +1,54 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +public class Address { + private String street; + private String city; + private String postalCode; + + public Address() { + } + + private String country; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Address(String street, String city, String postalCode, String country) { + + this.street = street; + this.city = city; + this.postalCode = postalCode; + this.country = country; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/DeliveryData.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/DeliveryData.java new file mode 100644 index 0000000000..9501649a05 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/DeliveryData.java @@ -0,0 +1,54 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; +import com.googlecode.jmapper.annotations.JMapAccessor; + +public class DeliveryData { + private Address deliveryAddress; + @JMapAccessor(get = "isPrePaid", set = "setPrePaid") + private boolean isPrePaid; + private String trackingCode; + private int expectedDeliveryTimeInDays; + + public DeliveryData() { + } + + public Address getDeliveryAddress() { + return deliveryAddress; + } + + public void setDeliveryAddress(Address deliveryAddress) { + this.deliveryAddress = deliveryAddress; + } + + public boolean isPrePaid() { + return isPrePaid; + } + + public void setPrePaid(boolean prePaid) { + isPrePaid = prePaid; + } + + public String getTrackingCode() { + return trackingCode; + } + + public void setTrackingCode(String trackingCode) { + this.trackingCode = trackingCode; + } + + public int getExpectedDeliveryTimeInDays() { + return expectedDeliveryTimeInDays; + } + + public void setExpectedDeliveryTimeInDays(int expectedDeliveryTimeInDays) { + this.expectedDeliveryTimeInDays = expectedDeliveryTimeInDays; + } + + public DeliveryData(Address deliveryAddress, boolean isPrePaid, String trackingCode, int expectedDeliveryTimeInDays) { + this.deliveryAddress = deliveryAddress; + this.isPrePaid = isPrePaid; + this.trackingCode = trackingCode; + this.expectedDeliveryTimeInDays = expectedDeliveryTimeInDays; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Discount.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Discount.java new file mode 100644 index 0000000000..603432dfed --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Discount.java @@ -0,0 +1,44 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.math.BigDecimal; +public class Discount { + private String startTime; + private String endTime; + private BigDecimal discountPrice; + + public Discount() { + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + public BigDecimal getDiscountPrice() { + return discountPrice; + } + + public void setDiscountPrice(BigDecimal discountPrice) { + this.discountPrice = discountPrice; + } + + public Discount(String startTime, String endTime, BigDecimal discountPrice) { + + this.startTime = startTime; + this.endTime = endTime; + this.discountPrice = discountPrice; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/OrderStatus.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/OrderStatus.java new file mode 100644 index 0000000000..962c91a6c4 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/OrderStatus.java @@ -0,0 +1,7 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +public enum OrderStatus { + CREATED, CONFIRMED, COLLECTING, IN_TRANSPORT, FINISHED +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/PaymentType.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/PaymentType.java new file mode 100644 index 0000000000..fbb4c82afc --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/PaymentType.java @@ -0,0 +1,7 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +public enum PaymentType { + CASH, CARD, TRANSFER +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Product.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Product.java new file mode 100644 index 0000000000..5feccb97dc --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Product.java @@ -0,0 +1,76 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +import java.math.BigDecimal; + +public class Product { + private BigDecimal price; + private int quantity; + + public Product() { + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isAvailable() { + return available; + } + + public void setAvailable(boolean available) { + this.available = available; + } + + public RefundPolicy getRefundPolicy() { + return refundPolicy; + } + + public void setRefundPolicy(RefundPolicy refundPolicy) { + this.refundPolicy = refundPolicy; + } + + private String name; + + public Product(BigDecimal price, int quantity, String name, String description, boolean available, RefundPolicy refundPolicy) { + this.price = price; + this.quantity = quantity; + this.name = name; + this.description = description; + this.available = available; + this.refundPolicy = refundPolicy; + } + + String description; + boolean available; + private RefundPolicy refundPolicy; +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/RefundPolicy.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/RefundPolicy.java new file mode 100644 index 0000000000..5111e27b54 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/RefundPolicy.java @@ -0,0 +1,48 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; +import com.googlecode.jmapper.annotations.JMapAccessor; + +import java.util.List; + +public class RefundPolicy { + @JMapAccessor(get = "isRefundable", set = "setRefundable") + private boolean isRefundable; + private int refundTimeInDays; + + public RefundPolicy() { + } + + public boolean isRefundable() { + return isRefundable; + } + + public void setRefundable(boolean refundable) { + isRefundable = refundable; + } + + public int getRefundTimeInDays() { + return refundTimeInDays; + } + + public void setRefundTimeInDays(int refundTimeInDays) { + this.refundTimeInDays = refundTimeInDays; + } + + public List getNotes() { + return notes; + } + + public void setNotes(List notes) { + this.notes = notes; + } + + public RefundPolicy(boolean isRefundable, int refundTimeInDays, List notes) { + + this.isRefundable = isRefundable; + this.refundTimeInDays = refundTimeInDays; + this.notes = notes; + } + + private List notes; +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Review.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Review.java new file mode 100644 index 0000000000..8e2630b672 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Review.java @@ -0,0 +1,63 @@ +package com.baeldung.performancetests.model.source; + +public class Review { + + int shippingGrade; + int pricingGrade; + int serviceGrade; + User reviewingUser; + String note; + + public int getShippingGrade() { + return shippingGrade; + } + + public void setShippingGrade(int shippingGrade) { + this.shippingGrade = shippingGrade; + } + + public int getPricingGrade() { + return pricingGrade; + } + + public void setPricingGrade(int pricingGrade) { + this.pricingGrade = pricingGrade; + } + + public int getServiceGrade() { + return serviceGrade; + } + + public void setServiceGrade(int serviceGrade) { + this.serviceGrade = serviceGrade; + } + + public User getReviewingUser() { + return reviewingUser; + } + + public void setReviewingUser(User reviewingUser) { + this.reviewingUser = reviewingUser; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public Review() { + + } + + public Review(int shippingGrade, int pricingGrade, int serviceGrade, User reviewingUser, String note) { + + this.shippingGrade = shippingGrade; + this.pricingGrade = pricingGrade; + this.serviceGrade = serviceGrade; + this.reviewingUser = reviewingUser; + this.note = note; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Shop.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Shop.java new file mode 100644 index 0000000000..d35681933b --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/Shop.java @@ -0,0 +1,55 @@ +package com.baeldung.performancetests.model.source; + +import java.util.List; + +public class Shop { + + private String shopName; + private Address shopAddres; + + public String getShopName() { + return shopName; + } + + public void setShopName(String shopName) { + this.shopName = shopName; + } + + public Address getShopAddres() { + return shopAddres; + } + + public void setShopAddres(Address shopAddres) { + this.shopAddres = shopAddres; + } + + public Shop() { + } + + public String getShopUrl() { + return shopUrl; + } + + public void setShopUrl(String shopUrl) { + this.shopUrl = shopUrl; + } + + public List getReviews() { + return reviews; + } + + public void setReviews(List reviews) { + this.reviews = reviews; + } + + public Shop(String shopName, Address shopAddres, String shopUrl, List reviews) { + + this.shopName = shopName; + this.shopAddres = shopAddres; + this.shopUrl = shopUrl; + this.reviews = reviews; + } + + private String shopUrl; + private List reviews; +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceCode.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceCode.java new file mode 100644 index 0000000000..52934d6e0b --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceCode.java @@ -0,0 +1,22 @@ +package com.baeldung.performancetests.model.source; + +public class SourceCode { + String code; + + public SourceCode() { + } + + public String getCode() { + + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public SourceCode(String code) { + + this.code = code; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceOrder.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceOrder.java new file mode 100644 index 0000000000..e83a145f6f --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/SourceOrder.java @@ -0,0 +1,118 @@ +package com.baeldung.performancetests.model.source; + + +import java.util.List; +public class SourceOrder { + private String orderFinishDate; + private PaymentType paymentType; + private Discount discount; + private DeliveryData deliveryData; + private User orderingUser; + private List orderedProducts; + private Shop offeringShop; + private int orderId; + private OrderStatus status; + private String orderDate; + public SourceOrder() { + } + + public User getOrderingUser() { + return orderingUser; + } + + public void setOrderingUser(User orderingUser) { + this.orderingUser = orderingUser; + } + + public List getOrderedProducts() { + return orderedProducts; + } + + public void setOrderedProducts(List orderedProducts) { + this.orderedProducts = orderedProducts; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public String getOrderDate() { + return orderDate; + } + + public void setOrderDate(String orderDate) { + this.orderDate = orderDate; + } + + public String getOrderFinishDate() { + return orderFinishDate; + } + + public void setOrderFinishDate(String orderFinishDate) { + this.orderFinishDate = orderFinishDate; + } + + public PaymentType getPaymentType() { + return paymentType; + } + + public void setPaymentType(PaymentType paymentType) { + this.paymentType = paymentType; + } + + public Discount getDiscount() { + return discount; + } + + public void setDiscount(Discount discount) { + this.discount = discount; + } + + public DeliveryData getDeliveryData() { + return deliveryData; + } + + public void setDeliveryData(DeliveryData deliveryData) { + this.deliveryData = deliveryData; + } + + public Shop getOfferingShop() { + return offeringShop; + } + + public void setOfferingShop(Shop offeringShop) { + this.offeringShop = offeringShop; + } + + + + + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public SourceOrder(OrderStatus status, String orderDate, String orderFinishDate, PaymentType paymentType, Discount discount, DeliveryData deliveryData, User orderingUser, List orderedProducts, Shop offeringShop, int orderId) { + + this.status = status; + this.orderDate = orderDate; + this.orderFinishDate = orderFinishDate; + this.paymentType = paymentType; + this.discount = discount; + this.deliveryData = deliveryData; + this.orderingUser = orderingUser; + this.orderedProducts = orderedProducts; + this.offeringShop = offeringShop; + this.orderId = orderId; + } + + +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/model/source/User.java b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/User.java new file mode 100644 index 0000000000..8c50acb560 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/model/source/User.java @@ -0,0 +1,42 @@ +package com.baeldung.performancetests.model.source; + +import com.googlecode.jmapper.annotations.JGlobalMap; + +public class User { + private String username; + private String email; + private AccountStatus userAccountStatus; + + public User(String username, String email, AccountStatus userAccountStatus) { + this.username = username; + this.email = email; + this.userAccountStatus = userAccountStatus; + } + + public User() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public AccountStatus getUserAccountStatus() { + return userAccountStatus; + } + + public void setUserAccountStatus(AccountStatus userAccountStatus) { + this.userAccountStatus = userAccountStatus; + } +} diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/modelmapper/ModelMapperConverter.java b/performance-tests/src/main/java/com/baeldung/performancetests/modelmapper/ModelMapperConverter.java new file mode 100644 index 0000000000..e3f0426e39 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/modelmapper/ModelMapperConverter.java @@ -0,0 +1,26 @@ +package com.baeldung.performancetests.modelmapper; + +import com.baeldung.performancetests.Converter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; +import org.modelmapper.ModelMapper; + + public class ModelMapperConverter implements Converter { + private ModelMapper modelMapper; + + public ModelMapperConverter() { + modelMapper = new ModelMapper(); + } + + @Override + public Order convert(SourceOrder sourceOrder) { + return modelMapper.map(sourceOrder, Order.class); + } + + @Override + public DestinationCode convert(SourceCode sourceCode) { + return modelMapper.map(sourceCode, DestinationCode.class); + } + } diff --git a/performance-tests/src/main/java/com/baeldung/performancetests/orika/OrikaConverter.java b/performance-tests/src/main/java/com/baeldung/performancetests/orika/OrikaConverter.java new file mode 100644 index 0000000000..994a1830d5 --- /dev/null +++ b/performance-tests/src/main/java/com/baeldung/performancetests/orika/OrikaConverter.java @@ -0,0 +1,31 @@ +package com.baeldung.performancetests.orika; + +import com.baeldung.performancetests.Converter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.destination.Order; +import ma.glasnost.orika.MapperFacade; +import ma.glasnost.orika.MapperFactory; +import ma.glasnost.orika.impl.DefaultMapperFactory; + +public class OrikaConverter implements Converter{ + private MapperFacade mapperFacade; + + public OrikaConverter() { + MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build(); + + mapperFactory.classMap(Order.class, SourceOrder.class).field("orderStatus", "status").byDefault().register(); + mapperFacade = mapperFactory.getMapperFacade(); + } + + @Override + public Order convert(SourceOrder sourceOrder) { + return mapperFacade.map(sourceOrder, Order.class); + } + + @Override + public DestinationCode convert(SourceCode sourceCode) { + return mapperFacade.map(sourceCode, DestinationCode.class); + } +} diff --git a/performance-tests/src/main/resources/dozer-mapping.xml b/performance-tests/src/main/resources/dozer-mapping.xml new file mode 100644 index 0000000000..7fd7e78e9f --- /dev/null +++ b/performance-tests/src/main/resources/dozer-mapping.xml @@ -0,0 +1,25 @@ + + + + + true + MM/dd/yyyy HH:mm + true + + + + com.baeldung.performancetests.model.source.SourceOrder + com.baeldung.performancetests.model.destination.Order + + status + orderStatus + + + + com.baeldung.performancetests.model.source.SourceCode + com.baeldung.performancetests.model.destination.DestinationCode + + \ No newline at end of file diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java new file mode 100644 index 0000000000..9a45f032a6 --- /dev/null +++ b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java @@ -0,0 +1,193 @@ +package com.baeldung.performancetests.benchmark; + +import com.baeldung.performancetests.dozer.DozerConverter; +import com.baeldung.performancetests.jmapper.JMapperConverter; +import com.baeldung.performancetests.mapstruct.MapStructConverter; +import com.baeldung.performancetests.model.destination.DestinationCode; +import com.baeldung.performancetests.model.source.*; +import com.baeldung.performancetests.model.destination.Order; +import com.baeldung.performancetests.modelmapper.ModelMapperConverter; +import com.baeldung.performancetests.orika.OrikaConverter; +import org.junit.Assert; +import org.junit.Test; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.RunnerException; + +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@State(Scope.Group) +public class MappingFrameworksPerformance { + SourceOrder sourceOrder = null; + SourceCode sourceCode = null; + @Setup + public void setUp() { + User user = new User("John", "John@doe.com", AccountStatus.ACTIVE); + RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections.singletonList("Refundable only if not used!")); + + Product product = new Product(BigDecimal.valueOf(10.99), + 100, + "Sample Product", + "Sample Product to be sold", + true, + refundPolicy + ); + + Discount discount = new Discount(Instant.now().toString(), Instant.now().toString(), BigDecimal.valueOf(5.99)); + Address deliveryAddress = new Address("Washington Street 5", "New York", "55045", "USA"); + DeliveryData deliveryData = new DeliveryData(deliveryAddress, true, "", 10); + Address shopAddress = new Address("Roosvelt Street 9", "Boston", "55042", "USA"); + User reviewingUser = new User("John", "Johhny@John.com", AccountStatus.ACTIVE); + User negativeReviewingUser = new User("Carl", "Carl@Coral.com", AccountStatus.ACTIVE); + Review review = new Review(5, 5, 5, reviewingUser, "The best shop I've ever bought things in"); + + Review negativeReview = new Review(1, 1, 1, negativeReviewingUser, "I will never buy anything again here!"); + + List reviewList = new ArrayList<>(); + reviewList.add(review); + reviewList.add(negativeReview); + Shop shop = new Shop("Super Shop", shopAddress,"www.super-shop.com",reviewList); + + sourceOrder = new SourceOrder(OrderStatus.CONFIRMED, + Instant.now().toString(), + Instant.MAX.toString(), + PaymentType.TRANSFER, + discount, + deliveryData, + user, + Collections.singletonList(product), + shop, + 1 + ); + + sourceCode = new SourceCode("This is source code!"); + } + + + public void main(String[] args) throws IOException, RunnerException { + org.openjdk.jmh.Main.main(args); + } + + + @Benchmark + @Group("realLifeTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void orikaMapperRealLifeBenchmark() { + OrikaConverter orikaConverter = new OrikaConverter(); + Order mappedOrder = orikaConverter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + + } + + @Benchmark + @Group("realLifeTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void jmapperRealLifeBenchmark() { + JMapperConverter jmapperConverter = new JMapperConverter(); + Order mappedOrder = jmapperConverter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + } + + @Benchmark + @Group("realLifeTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void modelMapperRealLifeBenchmark() { + ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); + Order mappedOrder = modelMapperConverter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + } + + + @Benchmark + @Group("realLifeTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void dozerMapperRealLifeBenchmark() { + DozerConverter dozerConverter = new DozerConverter(); + Order mappedOrder = dozerConverter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + + } + + @Benchmark + @Group("realLifeTest") + @Fork(value = 1, warmups = 1) + @BenchmarkMode(Mode.All) + public void mapStructRealLifeMapperBenchmark() { + MapStructConverter converter = MapStructConverter.MAPPER; + Order mappedOrder = converter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + } + + @Benchmark + @Group("simpleTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void orikaMapperSimpleBenchmark() { + OrikaConverter orikaConverter = new OrikaConverter(); + DestinationCode mappedCode = orikaConverter.convert(sourceCode); + Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + + } + + @Benchmark + @Group("simpleTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void jmapperSimpleBenchmark() { + JMapperConverter jmapperConverter = new JMapperConverter(); + DestinationCode mappedCode = jmapperConverter.convert(sourceCode); + Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + } + + @Benchmark + @Group("simpleTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void modelMapperBenchmark() { + ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); + DestinationCode mappedCode = modelMapperConverter.convert(sourceCode); + Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + } + + + @Benchmark + @Group("simpleTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void dozerMapperSimpleBenchmark() { + DozerConverter dozerConverter = new DozerConverter(); + Order mappedOrder = dozerConverter.convert(sourceOrder); + Assert.assertEquals(mappedOrder, sourceOrder); + + } + + @Benchmark + @Group("simpleTest") + @Fork(value = 1, warmups = 1) + @OutputTimeUnit(TimeUnit.MILLISECONDS) + @BenchmarkMode(Mode.All) + public void mapStructMapperSimpleBenchmark() { + MapStructConverter converter = MapStructConverter.MAPPER; + DestinationCode mappedCode = converter.convert(sourceCode); + Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + } + + +} diff --git a/performance-tests/src/test/resources/dozer-mapping.xml b/performance-tests/src/test/resources/dozer-mapping.xml new file mode 100644 index 0000000000..7484812431 --- /dev/null +++ b/performance-tests/src/test/resources/dozer-mapping.xml @@ -0,0 +1,21 @@ + + + + + true + MM/dd/yyyy HH:mm + true + + + + com.baeldung.performancetests.model.source.SourceOrder + com.baeldung.performancetests.model.destination.Order + + status + orderStatus + + + \ No newline at end of file diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 015fdc84de..610d6b8f09 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -29,13 +29,6 @@ ${cassandra-unit.version} - - - com.google.guava - guava - ${guava.version} - - diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 540b7ad7b9..84165564ba 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-spring + 0.0.1-SNAPSHOT + ../../parent-spring diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 55f1124531..26d5c6bddf 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-spring + 0.0.1-SNAPSHOT + ../../parent-spring diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index e687ee5f1f..f1c20344c1 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-spring + 0.0.1-SNAPSHOT + ../../parent-spring diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 6a7153b524..cb71d386e2 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -16,10 +16,12 @@ - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) - [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [Advanced Tagging Implementation with JPA] (http://www.baeldung.com/jpa-tagging-advanced) +- [Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) +- [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/pom.xml b/pom.xml index 5c89660e78..78e0fa925e 100644 --- a/pom.xml +++ b/pom.xml @@ -10,6 +10,9 @@ parent-boot-5 + parent-boot-2 + parent-spring + parent-java asm atomix apache-cayenne @@ -91,6 +94,7 @@ logging-modules/log-mdc logging-modules/log4j logging-modules/log4j2 + logging-modules/log4j2-programmatic-configuration logging-modules/logback lombok mapstruct @@ -252,6 +256,7 @@ persistence-modules/java-jdbi jersey java-spi + performance-tests @@ -284,6 +289,12 @@ ${junit.version} test + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + org.hamcrest hamcrest-core @@ -515,6 +526,7 @@ 1.2 2.5.0 1.3 + 5.0.2 \ No newline at end of file diff --git a/rxjava/pom.xml b/rxjava/pom.xml index 41f2c3f6f6..72d2859330 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -65,12 +66,6 @@ assertj-core ${assertj.version} - - com.google.guava - guava - 22.0 - test - com.jakewharton.rxrelay2 rxrelay diff --git a/saas/pom.xml b/saas/pom.xml index 6b34b99a5d..bb951ceda8 100644 --- a/saas/pom.xml +++ b/saas/pom.xml @@ -9,8 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -24,11 +25,6 @@ fugue ${atlassian.fugue.version} - - com.google.guava - guava - ${guava.version} - diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 7c078a8f92..9998dbf751 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -16,3 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) - [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) +- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) diff --git a/spring-5/README.md b/spring-5/README.md index d37927cfc7..de42d965f5 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -16,3 +16,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) - [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) +- [Spring Assert Statements](http://www.baeldung.com/spring-assert) diff --git a/spring-all/README.md b/spring-all/README.md index 0902a11a77..a3e1ca5464 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -12,7 +12,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Properties with Spring](http://www.baeldung.com/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) -- [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3/) +- [What's New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3) - [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) @@ -26,3 +26,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) - [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial) - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) +- [Quick Guide to the Spring @Order Annotation](http://www.baeldung.com/spring-order) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index ac66ecdad8..f9ced963e7 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -170,6 +170,7 @@ org.springframework.boot spring-boot-starter-thymeleaf + ${org.springframework.version} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java new file mode 100644 index 0000000000..4df1e2e73b --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java @@ -0,0 +1,36 @@ +package com.baeldung.contexts.config; + +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; + +public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { + + @Override + protected WebApplicationContext createRootApplicationContext() { + //If this is not the only class declaring a root context, we return null because it would clash + //with other classes, as there can only be a single root context. + + //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); + //rootContext.register(RootApplicationConfig.class); + //return rootContext; + return null; + } + + @Override + protected WebApplicationContext createServletApplicationContext() { + AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); + normalWebAppContext.register(NormalWebAppConfig.class); + return normalWebAppContext; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/api/*" }; + } + + @Override + protected String getServletName() { + return "normal-dispatcher"; + } +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java new file mode 100644 index 0000000000..0d2674d4f3 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java @@ -0,0 +1,16 @@ +package com.baeldung.contexts.config; + +import org.springframework.web.context.AbstractContextLoaderInitializer; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; + +public class AnnotationsBasedApplicationInitializer extends AbstractContextLoaderInitializer { + + @Override + protected WebApplicationContext createRootApplicationContext() { + AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); + rootContext.register(RootApplicationConfig.class); + return rootContext; + } + +} \ No newline at end of file diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java index c3ff90cf39..09e0742394 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java @@ -5,31 +5,36 @@ import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -@Configuration public class ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { - AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - rootContext.register(RootApplicationConfig.class); - servletContext.addListener(new ContextLoaderListener(rootContext)); - - AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); - normalWebAppContext.register(NormalWebAppConfig.class); - ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); - normal.setLoadOnStartup(1); - normal.addMapping("/api/*"); - - AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); - secureWebAppContext.register(SecureWebAppConfig.class); - ServletRegistration.Dynamic secure = servletContext.addServlet("secure-webapp", new DispatcherServlet(secureWebAppContext)); - secure.setLoadOnStartup(1); - secure.addMapping("/s/api/*"); + //Here, we can define a root context and register servlets, among other things. + //However, since we've later defined other classes to do the same and they would clash, + //we leave this commented out. + + //Root XML Context + //XmlWebApplicationContext rootContext = new XmlWebApplicationContext(); + //rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml"); + //Annotations Context + //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); + //rootContext.register(RootApplicationConfig.class); + //Registration + //servletContext.addListener(new ContextLoaderListener(rootContext)); + + //Dispatcher Servlet + //XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext(); + //normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml"); + //ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); + //normal.setLoadOnStartup(1); + //normal.addMapping("/api/*"); } } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java new file mode 100644 index 0000000000..89ce0153f5 --- /dev/null +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.contexts.config; + +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; + +public class SecureAnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { + + @Override + protected WebApplicationContext createRootApplicationContext() { + return null; + } + + @Override + protected WebApplicationContext createServletApplicationContext() { + AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); + secureWebAppContext.register(SecureWebAppConfig.class); + return secureWebAppContext; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/s/api/*" }; + } + + + @Override + protected String getServletName() { + return "secure-dispatcher"; + } + +} diff --git a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index dd70ce8e97..fbe3dfb398 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -35,7 +35,7 @@ public class HelloWorldController { @RequestMapping(path = "/welcome") public ModelAndView helloWorld() { processContext(); - String message = "
" + "

" + greeterService.greet() + "

"; + String message = "
" + "

Normal " + greeterService.greet() + "

"; return new ModelAndView("welcome", "message", message); } } diff --git a/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java b/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java index b46ace91ae..4ebf2d55e0 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java +++ b/spring-all/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java @@ -43,7 +43,7 @@ public class HelloWorldSecureController { @RequestMapping(path = "/welcome") public ModelAndView helloWorld() { processContext(); - String message = "
" + "

" + greeterService.greet() + "

"; + String message = "
" + "

Secure " + greeterService.greet() + "

"; return new ModelAndView("welcome", "message", message); } } diff --git a/spring-all/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java new file mode 100644 index 0000000000..8bf23de2cc --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/config/ApplicationCacheConfig.java @@ -0,0 +1,30 @@ +package org.baeldung.caching.config; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Arrays; + +@EnableCaching +@Configuration +public class ApplicationCacheConfig { + + @Bean + public CacheManager cacheManager() { + SimpleCacheManager cacheManager = new SimpleCacheManager(); + Cache booksCache = new ConcurrentMapCache("books"); + cacheManager.setCaches(Arrays.asList(booksCache)); + return cacheManager; + } + + @Bean("customKeyGenerator") + public KeyGenerator keyGenerator() { + return new CustomKeyGenerator(); + } +} diff --git a/spring-all/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java b/spring-all/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java new file mode 100644 index 0000000000..c1da9493e0 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/config/CustomKeyGenerator.java @@ -0,0 +1,14 @@ +package org.baeldung.caching.config; + +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.util.StringUtils; + +import java.lang.reflect.Method; + +public class CustomKeyGenerator implements KeyGenerator { + + public Object generate(Object target, Method method, Object... params) { + return target.getClass().getSimpleName() + "_" + method.getName() + "_" + + StringUtils.arrayToDelimitedString(params, "_"); + } +} diff --git a/spring-all/src/main/java/org/baeldung/caching/example/BookService.java b/spring-all/src/main/java/org/baeldung/caching/example/BookService.java new file mode 100644 index 0000000000..26118d61de --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/example/BookService.java @@ -0,0 +1,21 @@ +package org.baeldung.caching.example; + +import org.baeldung.model.Book; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class BookService { + + @Cacheable(value="books", keyGenerator="customKeyGenerator") + public List getBooks() { + List books = new ArrayList(); + books.add(new Book(1, "The Counterfeiters", "André Gide")); + books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen")); + return books; + } + +} diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index ec6cf19785..3dc4db53c0 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -19,10 +19,13 @@ public class StudentControllerConfig implements WebApplicationInitializer { root.setServletContext(sc); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + //Manages the lifecycle of the root application context. + //Conflicts with other root contexts in the application, so we've manually set the parent below. + //sc.addListener(new ContextLoaderListener(root)); - DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); + webApplicationContext.setParent(root); + DispatcherServlet dv = new DispatcherServlet(webApplicationContext); ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); appServlet.setLoadOnStartup(1); diff --git a/spring-all/src/main/java/org/baeldung/model/Book.java b/spring-all/src/main/java/org/baeldung/model/Book.java new file mode 100644 index 0000000000..9305ce9653 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/model/Book.java @@ -0,0 +1,41 @@ +package org.baeldung.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/spring-all/src/main/java/org/baeldung/order/Average.java b/spring-all/src/main/java/org/baeldung/order/Average.java new file mode 100644 index 0000000000..d1d9117fb1 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/order/Average.java @@ -0,0 +1,15 @@ +package org.baeldung.order; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +@Order(Ordered.LOWEST_PRECEDENCE) +public class Average implements Rating { + + @Override + public int getRating() { + return 3; + } +} diff --git a/spring-all/src/main/java/org/baeldung/order/Excellent.java b/spring-all/src/main/java/org/baeldung/order/Excellent.java new file mode 100644 index 0000000000..e5f125593f --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/order/Excellent.java @@ -0,0 +1,14 @@ +package org.baeldung.order; + +import org.springframework.stereotype.Component; +import org.springframework.core.annotation.Order; + +@Component +@Order(1) +public class Excellent implements Rating { + + @Override + public int getRating() { + return 1; + } +} diff --git a/spring-all/src/main/java/org/baeldung/order/Good.java b/spring-all/src/main/java/org/baeldung/order/Good.java new file mode 100644 index 0000000000..3dd9852cc4 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/order/Good.java @@ -0,0 +1,14 @@ +package org.baeldung.order; + +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +@Order(2) +public class Good implements Rating { + + @Override + public int getRating() { + return 2; + } +} diff --git a/spring-all/src/main/java/org/baeldung/order/Rating.java b/spring-all/src/main/java/org/baeldung/order/Rating.java new file mode 100644 index 0000000000..dd0391a3d9 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/order/Rating.java @@ -0,0 +1,6 @@ +package org.baeldung.order; + +public interface Rating { + + int getRating(); +} diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java index 5ef83b8afd..a857783c60 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java @@ -26,11 +26,14 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("org.baeldung.spring.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + //Manages the lifecycle of the root application context. + //Conflicts with other root contexts in the application, so we've manually set the parent below. + //sc.addListener(new ContextLoaderListener(root)); // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); + GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); + webApplicationContext.setParent(root); + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(webApplicationContext)); appServlet.setLoadOnStartup(1); final Set mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { diff --git a/spring-all/src/main/webapp/WEB-INF/greeting.xml b/spring-all/src/main/webapp/WEB-INF/greeting.xml new file mode 100644 index 0000000000..3f0ae83455 --- /dev/null +++ b/spring-all/src/main/webapp/WEB-INF/greeting.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-all/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index 4ba9642448..0000000000 --- a/spring-all/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml index d358e2d62b..0a7a0919a8 100644 --- a/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml +++ b/spring-all/src/main/webapp/WEB-INF/normal-webapp-servlet.xml @@ -1,12 +1,9 @@ diff --git a/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml b/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml index cd79c64e79..af03661ebc 100644 --- a/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml +++ b/spring-all/src/main/webapp/WEB-INF/rootApplicationContext.xml @@ -10,7 +10,5 @@ - - - + \ No newline at end of file diff --git a/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml b/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml index 5bca724670..6cdd3971bf 100644 --- a/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml +++ b/spring-all/src/main/webapp/WEB-INF/secure-webapp-servlet.xml @@ -1,12 +1,9 @@ diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web.xml index 2050f28f81..42020e75c4 100644 --- a/spring-all/src/main/webapp/WEB-INF/web.xml +++ b/spring-all/src/main/webapp/WEB-INF/web.xml @@ -3,37 +3,54 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> - - - + + + + + + + + + + - + - + + - test-mvc + normal-webapp-annotations org.springframework.web.servlet.DispatcherServlet + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + contextConfigLocation - /WEB-INF/test-mvc.xml + com.baeldung.contexts.config.NormalWebAppConfig 1 - - test-mvc - /test/* + normal-webapp-annotations + /api-ann/* diff --git a/spring-all/src/main/webapp/WEB-INF/web_old.xml b/spring-all/src/main/webapp/WEB-INF/web_old.xml deleted file mode 100644 index 016369ad27..0000000000 --- a/spring-all/src/main/webapp/WEB-INF/web_old.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - Spring MVC Application - - - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - org.baeldung.spring.web.config - - - - org.springframework.web.context.ContextLoaderListener - - - - - mvc - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc - / - - - - index.html - - - \ No newline at end of file diff --git a/spring-all/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java b/spring-all/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java new file mode 100644 index 0000000000..a624f757fc --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/order/RatingRetrieverUnitTest.java @@ -0,0 +1,37 @@ +package org.baeldung.order; + + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +public class RatingRetrieverUnitTest { + + @Configuration + @ComponentScan(basePackages = {"org.baeldung.order"}) + static class ContextConfiguration {} + + @Autowired + private List ratings; + + @Test + public void givenOrderOnComponents_whenInjected_thenAutowireByOrderValue() { + assertThat(ratings.get(0).getRating(), is(equalTo(1))); + assertThat(ratings.get(1).getRating(), is(equalTo(2))); + assertThat(ratings.get(2).getRating(), is(equalTo(3))); + } + +} diff --git a/spring-boot-admin/README.md b/spring-boot-admin/README.md index 622533a6ad..73ce857059 100644 --- a/spring-boot-admin/README.md +++ b/spring-boot-admin/README.md @@ -14,4 +14,9 @@ and the mail configuration from application.properties * mvn clean install * mvn spring-boot:run * starts on port 8081 -* basic auth client/client \ No newline at end of file +* basic auth client/client + + +### Relevant Articles: + +- [A Guide to Spring Boot Admin](http://www.baeldung.com/spring-boot-admin) diff --git a/spring-boot-autoconfiguration/.gitignore b/spring-boot-autoconfiguration/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-autoconfiguration/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot-autoconfiguration/README.MD b/spring-boot-autoconfiguration/README.MD new file mode 100644 index 0000000000..a71af54dff --- /dev/null +++ b/spring-boot-autoconfiguration/README.MD @@ -0,0 +1,6 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) \ No newline at end of file diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml new file mode 100644 index 0000000000..2687fcd969 --- /dev/null +++ b/spring-boot-autoconfiguration/pom.xml @@ -0,0 +1,108 @@ + + 4.0.0 + com.baeldung + spring-boot-autoconfiguration + 0.0.1-SNAPSHOT + war + spring-boot-auto-configuration + This is simple boot application demonstrating a custom auto-configuration + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + mysql + mysql-connector-java + 8.0.11 + + + + + spring-boot + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + 3.1.1 + 3.3.7-1 + 3.1.7 + 8.5.11 + + + \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java rename to spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java similarity index 73% rename from spring-boot/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java rename to spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java index f419dbf4fd..0c9d7060dd 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/AutoconfigurationApplication.java @@ -1,15 +1,12 @@ package com.baeldung.autoconfiguration.example; -import javax.annotation.security.RolesAllowed; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AutoconfigurationApplication { - @RolesAllowed("*") + public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); SpringApplication.run(AutoconfigurationApplication.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java rename to spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUser.java diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java rename to spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-boot/src/main/resources/META-INF/spring.factories rename to spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories diff --git a/spring-boot-autoconfiguration/src/main/resources/application.properties b/spring-boot-autoconfiguration/src/main/resources/application.properties new file mode 100644 index 0000000000..4456c78e5d --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto = update diff --git a/spring-boot/src/main/resources/mysql.properties b/spring-boot-autoconfiguration/src/main/resources/mysql.properties similarity index 58% rename from spring-boot/src/main/resources/mysql.properties rename to spring-boot-autoconfiguration/src/main/resources/mysql.properties index 27092f852f..74f1ee1373 100644 --- a/spring-boot/src/main/resources/mysql.properties +++ b/spring-boot-autoconfiguration/src/main/resources/mysql.properties @@ -1,5 +1,5 @@ usemysql=local -mysql-hibernate.dialect=org.hibernate.dialect.MySQLDialect +mysql-hibernate.dialect=org.hibernate.dialect.MySQL5Dialect mysql-hibernate.show_sql=true mysql-hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java diff --git a/spring-boot-cli/README.md b/spring-boot-cli/README.md index 4185415b39..85323da9b4 100644 --- a/spring-boot-cli/README.md +++ b/spring-boot-cli/README.md @@ -3,4 +3,4 @@ ## Spring Boot CLI ### Relevant Articles: -- [Introduction to Spring Boot CLI](http://www.baeldung.com/) +- [Introduction to Spring Boot CLI](http://www.baeldung.com/spring-boot-cli) diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath index 60dbd696eb..88c3910e93 100644 --- a/spring-boot/.factorypath +++ b/spring-boot/.factorypath @@ -1,51 +1,50 @@ - - - - - - - - - + + + + + + + + + + + + + - - - - - - - + + + + + + - - - - - + + + + - + - + - - - - - - - - - - - - - - + + + + + + + + + + + - + @@ -53,53 +52,59 @@ - + - - - - + + + + + - - - - - - - - - - - + + + + + + + + + + + + + - + - - - - - - - - - - + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + @@ -108,47 +113,56 @@ - - - - + + + - - - + + + + + + + + + - - - - - - + + + + + + - + + + + + - - - + + + - + - - - - - - + + + + + + diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 7e68e30a47..72da255b95 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -20,7 +20,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Dynamic DTO Validation Config Retrieved from DB](http://www.baeldung.com/spring-dynamic-dto-validation) - [Custom Information in Spring Boot Info Endpoint](http://www.baeldung.com/spring-boot-info-actuator-custom) - [Using @JsonComponent in Spring Boot](http://www.baeldung.com/spring-boot-jsoncomponent) -- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) - [Testing in Spring Boot](http://www.baeldung.com/spring-boot-testing) - [Guide to @ConfigurationProperties in Spring Boot](http://www.baeldung.com/configuration-properties-in-spring-boot) - [How to Get All Spring-Managed Beans?](http://www.baeldung.com/spring-show-all-beans) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 127ac455e1..afc80eb68b 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -33,11 +33,6 @@ spring-boot-starter-actuator - - org.springframework.boot - spring-boot-starter-security - - com.graphql-java graphql-spring-boot-starter @@ -78,7 +73,6 @@ com.h2database h2 - ${h2.version} @@ -125,22 +119,14 @@ provided - - mysql - mysql-connector-java - ${mysql-connector-java.version} - - org.springframework spring-websocket - ${spring.version} org.springframework spring-messaging - ${spring.version} @@ -186,7 +172,6 @@ pl.project13.maven git-commit-id-plugin - ${git-commit-id-plugin.version} @@ -233,16 +218,12 @@ org.baeldung.demo.DemoApplication - 4.3.4.RELEASE - 2.2.1 3.1.1 3.3.7-1 3.1.7 8.5.11 - 1.4.194 2.4.1.Final 1.9.0 - 6.0.6 \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index 774eb69889..b4d416dd96 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -4,8 +4,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - /** * using the following annotations are equivalent: *
  • @@ -16,7 +14,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration; * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) *
*/ -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication @ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 580498e831..8a39078aac 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -3,9 +3,7 @@ package com.baeldung.annotation.servletcomponentscan; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication @ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { diff --git a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java index 9dfab1192d..97165f2cf3 100644 --- a/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java +++ b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/controller/UserController.java @@ -6,6 +6,7 @@ import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -22,7 +23,7 @@ public class UserController { private static final Logger LOG = LoggerFactory.getLogger(UserController.class); - @RequestMapping("") + @GetMapping("") public List getAllUsers() { LOG.info("Fetching all the users"); return Arrays.asList( diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index 26f0a60bff..c4a83cc2d9 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -4,7 +4,7 @@ import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import com.baeldung.displayallbeans.service.FooService; @@ -13,7 +13,7 @@ public class FooController { @Autowired private FooService fooService; - @RequestMapping(value = "/displayallbeans") + @GetMapping(value = "/displayallbeans") public String getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java index 0f8300a797..e079b9a665 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java @@ -2,7 +2,9 @@ package com.baeldung.dynamicvalidation; import com.baeldung.dynamicvalidation.dao.ContactInfoExpressionRepository; import com.baeldung.dynamicvalidation.model.ContactInfoExpression; -import org.apache.log4j.Logger; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.thymeleaf.util.StringUtils; @@ -13,7 +15,7 @@ import java.util.regex.Pattern; public class ContactInfoValidator implements ConstraintValidator { - private static final Logger LOG = Logger.getLogger(ContactInfoValidator.class); + private static final Logger LOG = LogManager.getLogger(ContactInfoValidator.class); @Autowired private ContactInfoExpressionRepository expressionRepository; diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java index acdd836c8c..361a7b1c03 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java @@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class DynamicValidationApp { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java b/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java index 45f9de78e4..5dd55ef077 100644 --- a/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java +++ b/spring-boot/src/main/java/com/baeldung/errorhandling/ErrorHandlingApplication.java @@ -1,14 +1,10 @@ package com.baeldung.errorhandling; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.servlet.handler.HandlerMappingIntrospector; -@SpringBootApplication(exclude = {MySQLAutoconfiguration.class}) +@SpringBootApplication @ComponentScan(basePackages = "com.baeldung.errorhandling") public class ErrorHandlingApplication { @@ -16,11 +12,4 @@ public class ErrorHandlingApplication { System.setProperty("spring.profiles.active", "errorhandling"); SpringApplication.run(ErrorHandlingApplication.class, args); } - - @Bean(name = "mvcHandlerMappingIntrospector") - public HandlerMappingIntrospector mvcHandlerMappingIntrospector(ApplicationContext context) { - return new HandlerMappingIntrospector(context); - } - - } diff --git a/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java b/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java index caa335ed23..e002ac045d 100644 --- a/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java +++ b/spring-boot/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java @@ -1,9 +1,9 @@ package com.baeldung.errorhandling.controllers; -import org.springframework.boot.autoconfigure.web.ErrorController; +import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; @@ -13,7 +13,7 @@ public class MyErrorController implements ErrorController { public MyErrorController() {} - @RequestMapping(value = "/error") + @GetMapping(value = "/error") public String handleError(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 84c96feb92..3489732b6f 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class FailureAnalyzerApplication { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index 4655e36f83..cd696eae70 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -6,9 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class) +@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java index 6d44e02ec2..9dca749319 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -1,7 +1,7 @@ package com.baeldung.git; import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; @@ -19,7 +19,7 @@ public class CommitInfoController { @Value("${git.commit.id}") private String commitId; - @RequestMapping("/commitId") + @GetMapping("/commitId") public Map getCommitId() { Map result = new HashMap<>(); result.put("Commit message", commitMessage); diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java index ca56437392..c92d1c32e6 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java @@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class InternationalizationApp { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java index 8a0b709e69..d93c826cfa 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java @@ -7,13 +7,13 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; @Configuration @ComponentScan(basePackages = "com.baeldung.internationalization.config") -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { diff --git a/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java index b865deea29..b5d53f0da3 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/App.java +++ b/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -3,9 +3,7 @@ package com.baeldung.intro; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); diff --git a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java index 2a82e58829..32f22f2cae 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -1,17 +1,17 @@ package com.baeldung.intro.controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { - @RequestMapping("/") + @GetMapping("/") public String root() { return "Index Page"; } - @RequestMapping("/local") + @GetMapping("/local") public String local() { return "/local"; } diff --git a/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java b/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java index a3fbc4a37e..daaeb8159b 100644 --- a/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java +++ b/spring-boot/src/main/java/com/baeldung/rss/ArticleRssController.java @@ -1,14 +1,14 @@ package com.baeldung.rss; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "/rss", produces = "application/*") public class ArticleRssController { - @RequestMapping(method = RequestMethod.GET) + @GetMapping public String articleFeed() { return "articleFeedView"; } diff --git a/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java b/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java index ee36ecdc51..aaa3188010 100644 --- a/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java +++ b/spring-boot/src/main/java/com/baeldung/rss/CustomContainer.java @@ -1,16 +1,17 @@ package com.baeldung.rss; -import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; -import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.stereotype.Component; @Component -public class CustomContainer implements EmbeddedServletContainerCustomizer { +public class CustomContainer implements WebServerFactoryCustomizer { @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(8080); - container.setContextPath(""); + public void customize(ConfigurableServletWebServerFactory factory) { + factory.setContextPath(""); + factory.setPort(8080); + } } \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/rss/RssApp.java b/spring-boot/src/main/java/com/baeldung/rss/RssApp.java index 2add7ed421..d3d3d0241f 100644 --- a/spring-boot/src/main/java/com/baeldung/rss/RssApp.java +++ b/spring-boot/src/main/java/com/baeldung/rss/RssApp.java @@ -1,13 +1,12 @@ package com.baeldung.rss; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import javax.annotation.security.RolesAllowed; -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication @ComponentScan(basePackages = "com.baeldung.rss") public class RssApp { diff --git a/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java b/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java index 237026780c..5b9ce1271e 100644 --- a/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java @@ -5,9 +5,9 @@ import java.time.LocalDateTime; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @@ -27,7 +27,7 @@ public class WarInitializerApplication extends SpringBootServletInitializer { @RestController public static class WarInitializerController { - @RequestMapping("/") + @GetMapping("/") public String handler(Model model) { model.addAttribute("date", LocalDateTime.now()); return "WarInitializerApplication is up and running!"; diff --git a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java index c8461e4efc..482e6f4b5a 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java @@ -3,11 +3,9 @@ package com.baeldung.servlets; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class ApplicationMain extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 8dea814bc7..e026f5c732 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -1,17 +1,17 @@ package com.baeldung.servlets.configuration; -import org.springframework.boot.web.support.ErrorPageFilter; +import org.springframework.boot.web.servlet.support.ErrorPageFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.resource.PathResourceResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration -public class WebMvcConfigure extends WebMvcConfigurerAdapter { +public class WebMvcConfigure implements WebMvcConfigurer { @Bean public ViewResolver getViewResolver() { diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java index e3c225d429..b34690b75e 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java @@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration; public class SpringRegistrationBeanServlet { @Bean - public ServletRegistrationBean genericCustomServlet() { - ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*"); + public ServletRegistrationBean genericCustomServlet() { + ServletRegistrationBean bean = new ServletRegistrationBean<>(new GenericCustomServlet(), "/springregistrationbeanservlet/*"); bean.setLoadOnStartup(1); return bean; } diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java index 9e460d03a8..2e7a0d756a 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java @@ -1,7 +1,7 @@ package com.baeldung.servlets.servlets.springboot.embedded; -import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; -import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -9,8 +9,8 @@ import org.springframework.context.annotation.Configuration; public class EmbeddedTomcatExample { @Bean - public EmbeddedServletContainerFactory servletContainer() { - TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); + public ConfigurableServletWebServerFactory servletContainer() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); return tomcat; } } diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/Application.java b/spring-boot/src/main/java/com/baeldung/shutdown/Application.java index 3d9c71a7b9..2225df8b34 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdown/Application.java +++ b/spring-boot/src/main/java/com/baeldung/shutdown/Application.java @@ -1,16 +1,13 @@ package com.baeldung.shutdown; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.system.ApplicationPidFileWriter; +import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; -import javax.annotation.security.RolesAllowed; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class Application { public static void main(String[] args) { @@ -24,7 +21,7 @@ public class Application { private static void closeApplication() { - ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(false).run(); + ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run(); System.out.println("Spring Boot application started"); ctx.getBean(TerminateBean.class); ctx.close(); @@ -32,7 +29,7 @@ public class Application { private static void exitApplication() { - ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(false).run(); + ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE).run(); int exitCode = SpringApplication.exit(ctx, () -> { // return the error code @@ -45,7 +42,7 @@ public class Application { } private static void writePID() { - SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(false); + SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class).web(WebApplicationType.NONE); app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid")); app.run(); } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java index ed99f65006..04c6305780 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java @@ -1,6 +1,7 @@ package com.baeldung.toggle; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -10,7 +11,7 @@ import org.springframework.stereotype.Component; @Component public class FeaturesAspect { - private static final Logger LOG = Logger.getLogger(FeaturesAspect.class); + private static final Logger LOG = LogManager.getLogger(FeaturesAspect.class); @Around(value = "@within(featureAssociation) || @annotation(featureAssociation)") public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable { diff --git a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java index df65033d6b..48a1ddf8d8 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java @@ -11,7 +11,7 @@ public class SalaryService { @FeatureAssociation(value = MyFeatures.EMPLOYEE_MANAGEMENT_FEATURE) public void increaseSalary(long id) { - Employee employee = employeeRepository.findOne(id); + Employee employee = employeeRepository.findById(id).orElse(null); employee.setSalary(employee.getSalary() + employee.getSalary() * 0.1); employeeRepository.save(employee); } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java index c269262ab2..27be6b7cca 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java @@ -5,9 +5,7 @@ import javax.annotation.security.RolesAllowed; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class ToggleApplication { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index 4b00247c4a..ce3eae7ce0 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -6,9 +6,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication @ComponentScan(basePackages = "com.baeldung.utils") public class UtilsApplication { diff --git a/spring-boot/src/main/java/com/baeldung/webjar/TestController.java b/spring-boot/src/main/java/com/baeldung/webjar/TestController.java index e8e7fd5ce9..e5404c7c7c 100644 --- a/spring-boot/src/main/java/com/baeldung/webjar/TestController.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/TestController.java @@ -2,12 +2,12 @@ package com.baeldung.webjar; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { - @RequestMapping(value = "/") + @GetMapping(value = "/") public String welcome(Model model) { return "index"; } diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index 5038c7e5f7..2397861f1d 100644 --- a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -3,9 +3,7 @@ package com.baeldung.webjar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class WebjarsdemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/boot/Application.java b/spring-boot/src/main/java/org/baeldung/boot/Application.java index 78e95455b8..c1b6558b26 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/Application.java +++ b/spring-boot/src/main/java/org/baeldung/boot/Application.java @@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class Application { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java index caf88c3be7..6d8708b06a 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java +++ b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -7,12 +7,12 @@ import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(final List argumentResolvers) { diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java index 817bae8d01..17457f4c20 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java @@ -7,8 +7,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; @@ -26,18 +25,18 @@ public class GenericEntityController { entityList.add(new GenericEntity(4l, "entity_4")); } - @RequestMapping("/entity/all") + @GetMapping("/entity/all") public List findAll() { return entityList; } - @RequestMapping(value = "/entity", method = RequestMethod.POST) + @PostMapping("/entity") public GenericEntity addEntity(GenericEntity entity) { entityList.add(entity); return entity; } - @RequestMapping("/entity/findby/{id}") + @GetMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); } diff --git a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java index 510e607dfa..e4e20de671 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ b/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java @@ -1,7 +1,7 @@ package org.baeldung.common.error; -import org.springframework.boot.autoconfigure.web.ErrorController; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.web.bind.annotation.GetMapping; public class MyCustomErrorController implements ErrorController { @@ -11,7 +11,7 @@ public class MyCustomErrorController implements ErrorController { // TODO Auto-generated constructor stub } - @RequestMapping(value = PATH) + @GetMapping(value = PATH) public String error() { return "Error heaven"; } diff --git a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java index ecabde7d9d..d503f5da6d 100644 --- a/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ b/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java @@ -1,6 +1,6 @@ package org.baeldung.common.error.controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @@ -9,12 +9,12 @@ public class ErrorController { public ErrorController() { } - @RequestMapping("/400") + @GetMapping("/400") String error400() { return "Error Code: 400 occured."; } - @RequestMapping("/errorHeaven") + @GetMapping("/errorHeaven") String errorHeaven() { return "You have reached the heaven of errors!!!"; } diff --git a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java index 9b5a0aa948..2d955bac9b 100644 --- a/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -1,20 +1,20 @@ package org.baeldung.common.properties; -import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; -import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; -import org.springframework.boot.web.servlet.ErrorPage; +import org.springframework.boot.web.server.ErrorPage; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; @Component -public class MyServletContainerCustomizationBean implements EmbeddedServletContainerCustomizer { +public class MyServletContainerCustomizationBean implements WebServerFactoryCustomizer { public MyServletContainerCustomizationBean() { } @Override - public void customize(ConfigurableEmbeddedServletContainer container) { + public void customize(ConfigurableServletWebServerFactory container) { container.setPort(8084); container.setContextPath("/springbootapp"); diff --git a/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java index c4b0d48244..4a88fcea07 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java @@ -4,10 +4,9 @@ import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; import org.springframework.context.annotation.Import; -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication @Import(GraphqlConfiguration.class) public class DemoApplication { diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java index d991d9a8a9..00fdbfaae4 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java @@ -2,10 +2,9 @@ package org.baeldung.demo.boottest; import java.util.List; -import javax.transaction.Transactional; - import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository @Transactional @@ -13,8 +12,6 @@ public interface EmployeeRepository extends JpaRepository { public Employee findByName(String name); - public Employee findById(Long id); - public List findAll(); } diff --git a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java index bd85234e02..a1639b29cc 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java @@ -2,10 +2,9 @@ package org.baeldung.demo.boottest; import java.util.List; -import javax.transaction.Transactional; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service @Transactional @@ -16,7 +15,7 @@ public class EmployeeServiceImpl implements EmployeeService { @Override public Employee getEmployeeById(Long id) { - return employeeRepository.findById(id); + return employeeRepository.findById(id).orElse(null); } @Override diff --git a/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java b/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java index 334730ccb0..66943f6461 100644 --- a/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java +++ b/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java @@ -12,7 +12,7 @@ public class FooService { private FooRepository fooRepository; public Foo getFooWithId(Integer id) throws Exception { - return fooRepository.findOne(id); + return fooRepository.findById(id).orElse(null); } public Foo getFooWithName(String name) { diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/CustomEndpoint.java b/spring-boot/src/main/java/org/baeldung/endpoints/CustomEndpoint.java deleted file mode 100644 index 222a54c6ef..0000000000 --- a/spring-boot/src/main/java/org/baeldung/endpoints/CustomEndpoint.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.endpoints; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.stereotype.Component; - -@Component -public class CustomEndpoint implements Endpoint> { - - public CustomEndpoint() { - - } - - public String getId() { - return "customEndpoint"; - } - - public boolean isEnabled() { - return true; - } - - public boolean isSensitive() { - return true; - } - - public List invoke() { - // Your logic to display the output - List messages = new ArrayList(); - messages.add("This is message 1"); - messages.add("This is message 2"); - return messages; - } -} diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/ListEndpoints.java b/spring-boot/src/main/java/org/baeldung/endpoints/ListEndpoints.java deleted file mode 100644 index 61571b4adf..0000000000 --- a/spring-boot/src/main/java/org/baeldung/endpoints/ListEndpoints.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.endpoints; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.AbstractEndpoint; -import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.stereotype.Component; - -@Component -public class ListEndpoints extends AbstractEndpoint> { - private List endpoints; - - @Autowired - public ListEndpoints(List endpoints) { - super("listEndpoints"); - this.endpoints = endpoints; - } - - public List invoke() { - return this.endpoints; - } -} \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java deleted file mode 100644 index 1a175aed48..0000000000 --- a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.endpoints; - -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.stereotype.Component; - -@Component -public class MyHealthCheck implements HealthIndicator { - - public Health health() { - int errorCode = check(); // perform some specific health check - if (errorCode != 0) { - return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); - } - return Health.up().build(); - } - - public int check() { - // Your logic to check health - return 1; - } -} diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 5cc697be65..30ac94221b 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -4,34 +4,27 @@ import org.baeldung.boot.controller.servlet.HelloWorldServlet; import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet; import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; -import org.baeldung.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController -@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) +@EnableAutoConfiguration @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" }) public class SpringBootApplication { private static ApplicationContext applicationContext; - @Autowired - private LoginService service; - - @RequestMapping("/") + @GetMapping("/") String home() { - service.login("admin", "admin".toCharArray()); return "TADA!!! You are in Spring Boot Actuator test application."; } diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java index 8ebda17f7d..cb0304fc41 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -4,9 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - -@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) +@EnableAutoConfiguration @ComponentScan(basePackageClasses = ConfigProperties.class) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginService.java b/spring-boot/src/main/java/org/baeldung/service/LoginService.java deleted file mode 100644 index 4f38e9cf09..0000000000 --- a/spring-boot/src/main/java/org/baeldung/service/LoginService.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.service; - -public interface LoginService { - public boolean login(String userName, char[] password); -} diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java deleted file mode 100644 index ed0090f8e4..0000000000 --- a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.stereotype.Service; - -@Service -public class LoginServiceImpl implements LoginService { - - private CounterService counterService; - - @Autowired - public LoginServiceImpl(CounterService counterService) { - this.counterService = counterService; - } - - public boolean login(String userName, char[] password) { - boolean success; - if (userName.equals("admin") && "secret".toCharArray().equals(password)) { - counterService.increment("counter.login.success"); - success = true; - } else { - counterService.increment("counter.login.failure"); - success = false; - } - return success; - } - -} diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index 70c68368b5..9132e710d1 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -7,10 +7,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; -import com.baeldung.autoconfiguration.MySQLAutoconfiguration; - @EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@SpringBootApplication public class Application { public static void main(String[] args) { System.setProperty("spring.config.name", "exception"); diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java index 45fbf2b623..92beab9430 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java @@ -1,6 +1,7 @@ package org.baeldung.websocket.client; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; @@ -18,7 +19,7 @@ import java.lang.reflect.Type; */ public class MyStompSessionHandler extends StompSessionHandlerAdapter { - private Logger logger = Logger.getLogger(MyStompSessionHandler.class); + private Logger logger = LogManager.getLogger(MyStompSessionHandler.class); @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 203f0ee3c5..04a4fbf9de 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -1,21 +1,22 @@ server.port=9090 -server.contextPath=/springbootapp -management.port=8081 -management.address=127.0.0.1 +server.servlet.contextPath=/springbootapp +management.server.port=8081 +management.server.address=127.0.0.1 #debug=true spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto = update -endpoints.shutdown.enabled=true -endpoints.jmx.domain=Spring Sample Application -endpoints.jmx.uniqueNames=true +management.endpoints.jmx.domain=Spring Sample Application +management.endpoints.jmx.uniqueNames=true + +management.endpoint.shutdown.enabled=true ##jolokia.config.debug=true ##endpoints.jolokia.enabled=true ##endpoints.jolokia.path=jolokia spring.jmx.enabled=true -endpoints.jmx.enabled=true +management.endpoints.jmx.enabled=true ## for pretty printing of json when endpoints accessed over HTTP http.mappers.jsonPrettyPrint=true @@ -26,11 +27,7 @@ info.app.description=This is my first spring boot application G1 info.app.version=1.0.0 info.java-vendor = ${java.specification.vendor} -## Spring Security Configurations -security.user.name=admin1 -security.user.password=secret1 management.security.role=SUPERUSER -management.endpoint.shutdown.enabled=true logging.level.org.springframework=INFO @@ -38,15 +35,12 @@ logging.level.org.springframework=INFO servlet.name=dispatcherExample servlet.mapping=/dispatcherExampleURL -#banner.charset=UTF-8 -#banner.location=classpath:banner.txt -#banner.image.location=classpath:banner.gif -#banner.image.width= //TODO -#banner.image.height= //TODO -#banner.image.margin= //TODO -#banner.image.invert= //TODO +#spring.banner.charset=UTF-8 +#spring.banner.location=classpath:banner.txt +#spring.banner.image.location=classpath:banner.gif +#spring.banner.image.width= //TODO +#spring.banner.image.height= //TODO +#spring.banner.image.margin= //TODO +#spring.banner.image.invert= //TODO contactInfoType=email - -endpoints.beans.id=springbeans -endpoints.beans.sensitive=false diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index afe7f8df31..aab4836b6f 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -4,9 +4,9 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; diff --git a/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationTest.java b/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationTest.java rename to spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java index a3ee30ef49..2361f422f3 100644 --- a/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationTest.java +++ b/spring-boot/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.servletinitializer.WarInitializerApplication.WarInitializerC @RunWith(SpringRunner.class) @WebMvcTest(controllers = WarInitializerController.class) -public class WarInitializerApplicationTest { +public class WarInitializerApplicationIntegrationTest { @Autowired private MockMvc mockMvc; diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index ca6230e8f5..471565b1c6 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -47,7 +47,7 @@ public class ToggleIntegrationTest { mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - emp = employeeRepository.findOne(1L); + emp = employeeRepository.findById(1L).orElse(null); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); } @@ -60,7 +60,7 @@ public class ToggleIntegrationTest { mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - emp = employeeRepository.findOne(1L); + emp = employeeRepository.findById(1L).orElse(null); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java index 2cb2f4dc10..290cfbe081 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootH2IntegrationTest.java @@ -22,7 +22,7 @@ public class SpringBootH2IntegrationTest { @Test public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); - GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId()); + GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); assertNotNull(foundEntity); assertEquals(genericEntity.getValue(), foundEntity.getValue()); } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java index d9c30c67da..c368cf5219 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java @@ -21,7 +21,7 @@ public class SpringBootJPAIntegrationTest { @Test public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); - GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId()); + GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); assertNotNull(foundEntity); assertEquals(genericEntity.getValue(), foundEntity.getValue()); } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java index 1d4ee262b0..128a05f103 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootProfileIntegrationTest.java @@ -24,7 +24,7 @@ public class SpringBootProfileIntegrationTest { @Test public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); - GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId()); + GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); assertNotNull(foundEntity); assertEquals(genericEntity.getValue(), foundEntity.getValue()); } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index f581052596..3042f95a46 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -43,13 +43,13 @@ public class EmployeeRepositoryIntegrationTest { Employee emp = new Employee("test"); entityManager.persistAndFlush(emp); - Employee fromDb = employeeRepository.findById(emp.getId()); + Employee fromDb = employeeRepository.findById(emp.getId()).orElse(null); assertThat(fromDb.getName()).isEqualTo(emp.getName()); } @Test public void whenInvalidId_thenReturnNull() { - Employee fromDb = employeeRepository.findById(-11L); + Employee fromDb = employeeRepository.findById(-11l).orElse(null); assertThat(fromDb).isNull(); } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index f004536c49..4eec62db13 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -50,9 +50,9 @@ public class EmployeeServiceImplIntegrationTest { Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null); - Mockito.when(employeeRepository.findById(john.getId())).thenReturn(john); + Mockito.when(employeeRepository.findById(john.getId()).orElse(null)).thenReturn(john); Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees); - Mockito.when(employeeRepository.findById(-99L)).thenReturn(null); + Mockito.when(employeeRepository.findById(-99L).orElse(null)).thenReturn(null); } @Test diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 2fa66a7929..93ff73bb37 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -1,108 +1,104 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - com.baeldung - spring-core - 0.0.1-SNAPSHOT - war - spring-core + 4.0.0 + com.baeldung + spring-core + 0.0.1-SNAPSHOT + war + spring-core - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + - - - org.mockito - mockito-all - ${mockito.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - com.google.guava - guava - ${guava.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter - 1.5.2.RELEASE - - - org.springframework.boot - spring-boot-test - ${mockito.spring.boot.version} - test - - - commons-io - commons-io - ${commons.io.version} - - + + + org.mockito + mockito-all + ${mockito.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.boot + spring-boot-starter + 1.5.2.RELEASE + + + org.springframework.boot + spring-boot-test + ${mockito.spring.boot.version} + test + + + commons-io + commons-io + ${commons.io.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + - - 1.10.19 - 1.4.4.RELEASE - 4.3.4.RELEASE - 1 - 20.0 - 2.6 - 1.16.12 - 2.5 - + + 1.10.19 + 1.4.4.RELEASE + 4.3.4.RELEASE + 1 + 20.0 + 2.6 + 1.16.12 + 2.5 + - - - java.net - https://maven.java.net/content/repositories/releases/ - - + + + java.net + https://maven.java.net/content/repositories/releases/ + + \ No newline at end of file diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index e314e7870e..804cf23a69 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -9,8 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 0ff8f3e9fd..24847aaec6 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring diff --git a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java new file mode 100644 index 0000000000..7434dde394 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.rest.core.config.RepositoryRestConfiguration; +import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; + +import com.baeldung.projections.CustomBook; + + +@Configuration +public class RestConfig extends RepositoryRestConfigurerAdapter{ + + @Override + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration){ + repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class); + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Book.java b/spring-data-rest/src/main/java/com/baeldung/models/Book.java index 06abfb8f4d..002a64e738 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Book.java +++ b/spring-data-rest/src/main/java/com/baeldung/models/Book.java @@ -4,6 +4,7 @@ import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @@ -20,12 +21,14 @@ public class Book { @Column(nullable = false) private String title; - + + private String isbn; + @ManyToOne @JoinColumn(name = "library_id") private Library library; - @ManyToMany(mappedBy = "books") + @ManyToMany(mappedBy = "books", fetch = FetchType.EAGER) private List authors; public Book() { @@ -52,6 +55,15 @@ public class Book { this.id = id; } + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public Library getLibrary() { return library; } diff --git a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java b/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java new file mode 100644 index 0000000000..1cd9c01383 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java @@ -0,0 +1,22 @@ +package com.baeldung.projections; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.rest.core.config.Projection; + +import com.baeldung.models.Author; +import com.baeldung.models.Book; + +@Projection(name = "customBook", types = { Book.class }) +public interface CustomBook { + @Value("#{target.id}") + long getId(); + + String getTitle(); + + List getAuthors(); + + @Value("#{target.getAuthors().size()}") + int getAuthorCount(); +} diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java b/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java index f9176032ab..34019a9d91 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java @@ -1,9 +1,10 @@ package com.baeldung.repositories; import org.springframework.data.repository.CrudRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.baeldung.models.Book; +import com.baeldung.projections.CustomBook; -public interface BookRepository extends CrudRepository { - -} +@RepositoryRestResource(excerptProjection = CustomBook.class) +public interface BookRepository extends CrudRepository {} diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java new file mode 100644 index 0000000000..4091fdf154 --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.projection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import com.baeldung.repositories.AuthorRepository; +import com.baeldung.repositories.BookRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) + +public class SpringDataProjectionIntegrationTest { + private static final String BOOK_ENDPOINT = "http://localhost:8080/books"; + private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors"; + + + @Autowired + private BookRepository bookRepo; + + @Autowired + private AuthorRepository authorRepo; + + @Before + public void setup(){ + if(bookRepo.findOne(1L) == null){ + Book book = new Book("Animal Farm"); + book.setIsbn("978-1943138425"); + book = bookRepo.save(book); + Author author = new Author("George Orwell"); + author = authorRepo.save(author); + author.setBooks(Arrays.asList(book)); + author = authorRepo.save(author); + } + } + + @Test + public void whenGetBook_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT+"/1"); + + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("isbn")); + assertFalse(response.asString().contains("authorCount")); +// System.out.println(response.asString()); + } + + + @Test + public void whenGetBookProjection_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook"); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); +// System.out.println(response.asString()); + } + + @Test + public void whenGetAllBooks_thenOK(){ + final Response response = RestAssured.get(BOOK_ENDPOINT); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); + // System.out.println(response.asString()); + } + + @Test + public void whenGetAuthorBooks_thenOK(){ + final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books"); + + assertEquals(200, response.getStatusCode()); + assertFalse(response.asString().contains("isbn")); + assertTrue(response.asString().contains("authorCount")); + System.out.println(response.asString()); + } +} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 1d4d2b0d71..9fa02f157d 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -1,102 +1,98 @@ - 4.0.0 - com.baeldung - spring-dispatcher-servlet - war - 1.0.0 - spring-dispatcher-servlet + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + 4.0.0 + com.baeldung + spring-dispatcher-servlet + war + 1.0.0 + spring-dispatcher-servlet - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + - - - org.springframework - spring-core - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson-mapper-asl.version} - - - javax.servlet - jstl - ${jstl.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp.jstl + jstl-api + ${jstl-api.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson-mapper-asl.version} + + + javax.servlet + jstl + ${jstl.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - spring-dispatcher-servlet - - - - org.apache.tomcat.maven - tomcat8-maven-plugin - ${tomcat8-maven-plugin.version} - - /springdispatcherservlet - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - false - - - - - + + spring-dispatcher-servlet + + + + org.apache.tomcat.maven + tomcat8-maven-plugin + ${tomcat8-maven-plugin.version} + + /springdispatcherservlet + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + - - 4.3.7.RELEASE - 3.0-r1655215 - 3.0.0 - + + 4.3.7.RELEASE + 3.0-r1655215 + 3.0.0 + \ No newline at end of file diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml index f36d6cd22a..eec78d21a6 100644 --- a/spring-groovy/pom.xml +++ b/spring-groovy/pom.xml @@ -12,26 +12,12 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring - - - UTF-8 - - + - - junit - junit - 3.8.1 - test - - - org.springframework - spring-core - 4.3.6.RELEASE - org.springframework.integration spring-integration-groovy @@ -71,4 +57,9 @@
+ + + UTF-8 + + diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 4284a253cc..88ee7fadd3 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -9,11 +9,12 @@ - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) - [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) -- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/) +- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) ### Quick Start diff --git a/spring-mvc-java/src/main/java/com/baeldung/cache/BookService.java b/spring-mvc-java/src/main/java/com/baeldung/cache/BookService.java new file mode 100644 index 0000000000..91c37ce5b6 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/cache/BookService.java @@ -0,0 +1,21 @@ +package com.baeldung.cache; + +import com.baeldung.model.Book; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class BookService { + + @Cacheable(value="books", keyGenerator="customKeyGenerator") + public List getBooks() { + List books = new ArrayList(); + books.add(new Book(1, "The Counterfeiters", "André Gide")); + books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen")); + return books; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/cache/CustomKeyGenerator.java b/spring-mvc-java/src/main/java/com/baeldung/cache/CustomKeyGenerator.java new file mode 100644 index 0000000000..2cb4bba95f --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/cache/CustomKeyGenerator.java @@ -0,0 +1,14 @@ +package com.baeldung.cache; + +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.util.StringUtils; + +import java.lang.reflect.Method; + +public class CustomKeyGenerator implements KeyGenerator { + + public Object generate(Object target, Method method, Object... params) { + return target.getClass().getSimpleName() + "_" + method.getName() + "_" + + StringUtils.arrayToDelimitedString(params, "_"); + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Book.java b/spring-mvc-java/src/main/java/com/baeldung/model/Book.java index b0cabe0125..bdfa1d835a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Book.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Book.java @@ -6,6 +6,15 @@ public class Book { private String author; private String title; + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + public int getId() { return id; } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationCacheConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationCacheConfig.java new file mode 100644 index 0000000000..e78506deaa --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ApplicationCacheConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.web.config; + +import com.baeldung.cache.CustomKeyGenerator; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Arrays; + +@EnableCaching +@Configuration +public class ApplicationCacheConfig extends CachingConfigurerSupport { + + @Bean + public CacheManager cacheManager() { + SimpleCacheManager cacheManager = new SimpleCacheManager(); + Cache booksCache = new ConcurrentMapCache("books"); + cacheManager.setCaches(Arrays.asList(booksCache)); + return cacheManager; + } + + @Bean("customKeyGenerator") + public KeyGenerator keyGenerator() { + return new CustomKeyGenerator(); + } +} diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 2f2d1e9dca..07d7221048 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -9,8 +9,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring @@ -95,12 +96,6 @@ ${springframework.version} test - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - com.rometools rome @@ -180,7 +175,6 @@ 2.3.27-incubating 1.2.5 5.0.2 - 5.0.2 1.0.2 1.9.0 2.9.4 diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml index a62a92aad8..94908d5d8b 100644 --- a/spring-mvc-tiles/pom.xml +++ b/spring-mvc-tiles/pom.xml @@ -9,10 +9,11 @@ Integrating Spring MVC with Apache Tiles - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 1a1ee66a1a..07d7182b7d 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -1,154 +1,150 @@ - 4.0.0 - com.baeldung - 0.1-SNAPSHOT - spring-mvc-velocity + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + spring-mvc-velocity - spring-mvc-velocity - war + spring-mvc-velocity + war - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + - + - + - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - org.springframework - spring-core - ${org.springframework.version} - - - org.springframework - spring-context-support - ${org.springframework.version} - + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework + spring-context-support + ${spring.version} + - + - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + - - org.apache.velocity - velocity - ${velocity.version} - + + org.apache.velocity + velocity + ${velocity.version} + - - org.apache.velocity - velocity-tools - ${velocity-tools.version} - - - commons-logging - commons-logging - - - + + org.apache.velocity + velocity-tools + ${velocity-tools.version} + + + commons-logging + commons-logging + + + - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito - ${powermock.version} - test - - - org.springframework - spring-test - ${org.springframework.version} - test - + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito + ${powermock.version} + test + + + org.springframework + spring-test + ${spring.version} + test + - + - - spring-mvc-velocity - - - src/main/resources - true - - + + spring-mvc-velocity + + + src/main/resources + true + + - + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - - - - - - + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + + + + + + - + - + - - - 4.3.4.RELEASE + + + 4.3.4.RELEASE - - 1.6.6 + + 1.6.6 - 4.4.5 - 4.5.2 + 4.4.5 + 4.5.2 - 3.1.0 - 1.7 - 2.0 - 2.9.0 + 3.1.0 + 1.7 + 2.0 + 2.9.0 - - 2.6 - 2.7 - 1.6.1 + + 2.6 + 2.7 + 1.6.1 - + \ No newline at end of file diff --git a/spring-remoting/README.md b/spring-remoting/README.md index da8238b034..7d344a3f27 100644 --- a/spring-remoting/README.md +++ b/spring-remoting/README.md @@ -5,6 +5,7 @@ - [Spring Remoting with Hessian and Burlap](http://www.baeldung.com/spring-remoting-hessian-burlap) - [Spring Remoting with AMQP](http://www.baeldung.com/spring-remoting-amqp) - [Spring Remoting with JMS](http://www.baeldung.com/spring-remoting-jms) +- [Spring Remoting with RMI](http://www.baeldung.com/spring-remoting-rmi) ### Overview This Maven project contains the Java source code for various modules used in the Spring Remoting series of articles. diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 97fc3274af..9ab9b4b718 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -7,24 +7,15 @@ spring-rest-embedded-tomcat war + com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + - - junit - junit - ${junit.version} - test - - - - org.springframework - spring-core - ${spring.version} - org.springframework spring-webmvc @@ -96,7 +87,6 @@ 5.0.2.RELEASE 2.19.1 - 4.12 2.9.2 1.8 1.8 diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index b1917fb225..23b0b0435b 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -9,12 +9,12 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) -- [HATEOAS for a Spring REST Service](http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/) +- [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring) - [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability) -- [ETags for REST with Spring](http://www.baeldung.com/2013/01/11/etags-for-rest-with-spring/) +- [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Integration Testing with the Maven Cargo plugin](http://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) -- [Introduction to Spring Data JPA](http://www.baeldung.com/2011/12/22/the-persistence-layer-with-spring-data-jpa/) -- [Project Configuration with Spring](http://www.baeldung.com/2012/03/12/project-configuration-with-spring/) +- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 58d974cdba..d56eb9949b 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -8,9 +8,10 @@ war - spring-boot-starter-parent - org.springframework.boot - 2.0.1.RELEASE + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java index f433b4f3c7..8f1a000acc 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java @@ -4,10 +4,10 @@ import com.baeldung.web.log.app.TaxiFareRequestInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { +public class TaxiFareMVCConfig implements WebMvcConfigurer { @Autowired private TaxiFareRequestInterceptor taxiFareRequestInterceptor; diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index 5a6f906204..b3e3cd179a 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -1,7 +1,15 @@ package org.baeldung.config; +import java.text.SimpleDateFormat; +import java.util.List; + import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; +import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -17,31 +25,30 @@ public class WebConfig implements WebMvcConfigurer { super(); } - // /* - @Override - public void configureMessageConverters(final List> messageConverters) { - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); - builder.indentOutput(true) - .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); - messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); - // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); - - // messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); - - // messageConverters.add(new ProtobufHttpMessageConverter()); - super.configureMessageConverters(messageConverters); - } - - private HttpMessageConverter createXmlHttpMessageConverter() { - final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - - final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); - xmlConverter.setMarshaller(xstreamMarshaller); - xmlConverter.setUnmarshaller(xstreamMarshaller); - - return xmlConverter; - } + @Override + public void configureMessageConverters(final List> messageConverters) { + final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); + builder.indentOutput(true) + .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); + messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); + // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + + // messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); + + // messageConverters.add(new ProtobufHttpMessageConverter()); + + } + + private HttpMessageConverter createXmlHttpMessageConverter() { + final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); + + final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); + xmlConverter.setMarshaller(xstreamMarshaller); + xmlConverter.setUnmarshaller(xstreamMarshaller); + + return xmlConverter; + } */ } diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 2ca383bdab..a320f6b137 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -1,225 +1,225 @@ - 4.0.0 - com.baeldung - spring-security-mvc-custom - 0.1-SNAPSHOT + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-security-mvc-custom + 0.1-SNAPSHOT + spring-security-mvc-custom + war - spring-security-mvc-custom - war + + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + - + - + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - + - + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - org.springframework - spring-tx - ${org.springframework.version} - - - org.springframework - spring-expression - ${org.springframework.version} - + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - + - + + javax.servlet + javax.servlet-api + ${javax.servlet.version} + provided + - - javax.servlet - javax.servlet-api - ${javax.servlet.version} - provided - + + javax.servlet + jstl + ${jstl.version} + runtime + - - javax.servlet - jstl - ${jstl.version} - runtime - + - + + + + + - - - - - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + com.google.guava + guava + ${guava.version} + - - com.google.guava - guava - ${guava.version} - + - + + org.springframework + spring-test + ${spring.version} + test + - - org.springframework - spring-test - ${org.springframework.version} - test - + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + + - - org.springframework.security - spring-security-test - ${org.springframework.security.version} - test - - + + spring-security-mvc-custom + + + src/main/resources + true + + - - spring-security-mvc-custom - - - src/main/resources - true - - + - + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - + - + - + + + 4.3.4.RELEASE + 4.2.0.RELEASE - - - 4.3.4.RELEASE - 4.2.0.RELEASE + + 5.2.5.Final + 5.1.40 - - 5.2.5.Final - 5.1.40 + + 5.3.3.Final + 3.1.0 + 1.2 - - 5.3.3.Final - 3.1.0 - 1.2 + + 19.0 + 3.5 + 2.9.1 - - 19.0 - 3.5 - 2.9.1 + 4.5.2 + 4.4.5 - 4.5.2 - 4.4.5 + 2.9.0 - 2.9.0 + + 2.6 + 2.7 + 1.6.1 - - 2.6 - 2.7 - 1.6.1 - - + \ No newline at end of file diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 8ea270cc9d..9387220b2a 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index e391bdfb60..ee11bf067c 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index e5c5e78bd4..5c3ac4b7c4 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 995f089d37..130778151f 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index 931528811a..6168740cb7 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index bfa8c1c7b9..bed3cd033d 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index 5898ba248e..d9b6a760b2 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -17,3 +17,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) - [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) +- [Spring Security for a REST API](http://www.baeldung.com/securing-a-restful-web-service-with-spring-security) diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 242b104c4a..e29012a3a5 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -9,10 +9,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/spring-security-thymeleaf/README.MD b/spring-security-thymeleaf/README.MD index 44d118f8a8..36007bce62 100644 --- a/spring-security-thymeleaf/README.MD +++ b/spring-security-thymeleaf/README.MD @@ -1,2 +1,6 @@ This module is for Spring Security Thymeleaf tutorial. -Jira BAEL-1556 \ No newline at end of file +Jira BAEL-1556 + +### Relevant Articles: + +- [Spring Security with Thymeleaf](http://www.baeldung.com/spring-security-thymeleaf) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 44393ac281..9346b74c89 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -10,9 +10,10 @@ - [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3) - [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) -- [Working with Booleans in Thymeleaf](http://www.baeldung.com/working-with-booleans-in-thymeleaf) +- [Working with Boolean in Thymeleaf](http://www.baeldung.com/thymeleaf-boolean) - [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) - [Conditionals in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-conditionals) +- [Iteration in Thymeleaf](http://www.baeldung.com/thymeleaf-iteration) ### Build the Project diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 9cbc3d7ed2..872b8ed352 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -7,10 +7,11 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + diff --git a/struts-2/pom.xml b/struts-2/pom.xml index 44cb6dae3d..bb23600446 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -8,10 +8,11 @@ struts - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + com.baeldung + parent-spring + 0.0.1-SNAPSHOT + ../parent-spring + src/main/java diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index dd1486be1d..cfffa29aec 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -17,21 +17,6 @@ ../../ - - UTF-8 - 1.8 - 5.1.0 - 1.0.1 - 4.12.1 - 2.8.2 - 1.4.196 - 2.11.0 - - 3.7.0 - 2.19.1 - 4.12 - 5.0.1.RELEASE - @@ -71,12 +56,6 @@ - - org.junit.jupiter - junit-jupiter-engine - ${junit.jupiter.version} - test - org.junit.platform junit-platform-runner @@ -99,12 +78,6 @@ h2 ${h2.version} - - junit - junit - ${junit4.version} - test - org.springframework spring-test @@ -119,4 +92,19 @@ + + UTF-8 + 1.8 + 5.1.0 + 1.0.1 + 4.12.1 + 2.8.2 + 1.4.196 + 2.11.0 + + 3.7.0 + 2.19.1 + 5.0.1.RELEASE + + diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 72c769ce4f..5a8d2289a4 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -14,6 +14,6 @@ - [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods) - [Mocking of Private Methods Using PowerMock](http://www.baeldung.com/powermock-private-method) - [Mock Final Classes and Methods with Mockito](http://www.baeldung.com/mockito-final) -- [Hamcrest Text Matchers] (http://www.baeldung.com/hamcrest-text-matchers) -- [Hamcrest File Matchers] (http://www.baeldung.com/hamcrest-file-matchers) +- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) +- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers) - [Hamcrest Custom Matchers](http://www.baeldung.com/hamcrest-custom-matchers) diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 3ba9fd0385..c2e5b4bf31 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -8,21 +8,15 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java - - com.google.guava - guava - ${guava.version} - - org.apache.commons commons-lang3 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index dc577b647b..3452cdae22 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -119,11 +119,6 @@ ${jackson-coreutils.version} - - com.google.guava - guava - ${guava.version} - com.github.fge btf diff --git a/testing-modules/rest-testing/README.md b/testing-modules/rest-testing/README.md index c6185de05f..ab038807bc 100644 --- a/testing-modules/rest-testing/README.md +++ b/testing-modules/rest-testing/README.md @@ -6,7 +6,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/) +- [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api) - [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) - [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) - [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing) diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index f9866496a4..8ebe86b9bb 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -9,21 +9,15 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java - - com.google.guava - guava - ${guava.version} - - commons-io commons-io diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index ecef105b01..6cf7ee223f 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -19,11 +19,6 @@ lambda-behave 0.4 - - com.google.guava - guava - ${guava.version} - org.assertj assertj-guava diff --git a/undertow/dependency-reduced-pom.xml b/undertow/dependency-reduced-pom.xml new file mode 100644 index 0000000000..a4a17f94d6 --- /dev/null +++ b/undertow/dependency-reduced-pom.xml @@ -0,0 +1,90 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + com.baeldung.undertow + undertow + undertow + 1.0-SNAPSHOT + http://maven.apache.org + + ${project.artifactId} + + + maven-shade-plugin + + + package + + shade + + + + + + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + org.hamcrest + hamcrest-library + 1.3 + test + + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.mockito + mockito-core + 2.8.9 + test + + + byte-buddy + net.bytebuddy + + + byte-buddy-agent + net.bytebuddy + + + objenesis + org.objenesis + + + + + + 1.8 + 1.8 + + diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 59e14810dd..c315efa713 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -15,12 +15,6 @@ - - com.google.guava - guava - ${guava.version} - - commons-io commons-io diff --git a/video-tutorials/pom.xml b/video-tutorials/pom.xml index ceabfa6a3b..cbaf5e3680 100644 --- a/video-tutorials/pom.xml +++ b/video-tutorials/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java diff --git a/vraptor/README.md b/vraptor/README.md index d547fc1274..0dc531ba8d 100644 --- a/vraptor/README.md +++ b/vraptor/README.md @@ -11,3 +11,8 @@ mvn tomcat7:run ``` Cuidado para *jamais* executar `mvn tomcat:run` pois ele usará um tomcat6 (incompatível). + + +### Relevant Article: + +- [Introduction to VRaptor in Java](http://www.baeldung.com/vraptor)