diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 27768d60fc..e0855155bc 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -74,6 +74,7 @@ maven-assembly-plugin + 3.3.0 package diff --git a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java index f529e219a6..0b70516146 100644 --- a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java +++ b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java @@ -10,5 +10,6 @@ public class CopyListServiceUnitTest { @Test(expected = UnsupportedOperationException.class) public void whenModifyCopyOfList_thenThrowsException() { List copyList = List.copyOf(Arrays.asList(1, 2, 3, 4)); + copyList.add(4); } } diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java new file mode 100644 index 0000000000..7c81142949 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java @@ -0,0 +1,11 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExampleCE { + + public static void main(String[] args) { + + //String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented + //array[0] = 2; + } + +} diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java new file mode 100644 index 0000000000..ce63fd6605 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java @@ -0,0 +1,16 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + } catch (ArrayStoreException e) { + // handle the exception + } + + } + +} diff --git a/core-java-modules/core-java-io-2/src/main/resources/logback.xml b/core-java-modules/core-java-io-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..f46a64b3cb --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java new file mode 100644 index 0000000000..ca6b25b3e7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java @@ -0,0 +1,60 @@ +package com.baeldung.algorithms.largestpowerof2; + +import org.nd4j.linalg.io.Assert; + +public class LargestPowerOf2 { + public long findLargestPowerOf2LessThanTheGivenNumber(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long firstPowerOf2 = 1; + long nextPowerOf2 = 2; + + while (nextPowerOf2 < input) { + firstPowerOf2 = nextPowerOf2; + nextPowerOf2 = nextPowerOf2 * 2; + } + return firstPowerOf2; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long temp = input; + if (input % 2 == 0) { + temp = input - 1; + } + + // Find log base 2 of a given number + long power = (long) (Math.log(temp) / Math.log(2)); + long result = (long) Math.pow(2, power); + + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + for (long i = input - 1; i > 1; i--) { + if ((i & (i - 1)) == 0) { + result = i; + break; + } + } + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + long powerOf2; + + for (long i = 0; i < Long.BYTES * 8; i++) { + powerOf2 = 1 << i; + if (powerOf2 >= input) { + break; + } + result = powerOf2; + } + return result; + } +} diff --git a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java new file mode 100644 index 0000000000..63f7b03cf7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.algorithms.largestpowerof2; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class LargestPowerOf2UnitTest { + private long input; + private long expectedResult; + + public LargestPowerOf2UnitTest(long input, long expectedResult) { + this.input = input; + this.expectedResult = expectedResult; + } + + @Parameterized.Parameters(name = "{index}: verifyLargestPowerOf2LessThanTheGivenNumber({0}) = {1}") + public static Collection data() { + return Arrays.asList(new Object[][] { { 2, 1 }, { 4, 2 }, { 500, 256 }, { 512, 256 }, { 1050, 1024 } }); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumber() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberUsingLogBase2() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitwiseAnd() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitShiftApproach() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInvalidInput_ShouldThrowException() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(1); + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections-2/README.md b/core-kotlin-modules/core-kotlin-collections-2/README.md new file mode 100644 index 0000000000..2dc180b5b3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/README.md @@ -0,0 +1,7 @@ +## Core Kotlin Collections + +This module contains articles about core Kotlin collections. + +### Relevant articles: + + diff --git a/core-kotlin-modules/core-kotlin-collections-2/pom.xml b/core-kotlin-modules/core-kotlin-collections-2/pom.xml new file mode 100644 index 0000000000..be462eed45 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + core-kotlin-collections-2 + core-kotlin-collections-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.6.1 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt new file mode 100644 index 0000000000..a09e101b59 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt @@ -0,0 +1,107 @@ +package com.baeldung.aggregate + +class AggregateOperations { + private val numbers = listOf(1, 15, 3, 8) + + fun countList(): Int { + return numbers.count() + } + + fun sumList(): Int { + return numbers.sum() + } + + fun averageList(): Double { + return numbers.average() + } + + fun maximumInList(): Int? { + return numbers.max() + } + + fun minimumInList(): Int? { + return numbers.min() + } + + fun maximumByList(): Int? { + return numbers.maxBy { it % 5 } + } + + fun minimumByList(): Int? { + return numbers.minBy { it % 5 } + } + + fun maximumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.maxWith(compareBy { it.length % 4 }) + } + + fun minimumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.minWith(compareBy { it.length % 4 }) + } + + fun sumByList(): Int { + return numbers.sumBy { it * 5 } + } + + fun sumByDoubleList(): Double { + return numbers.sumByDouble { it.toDouble() / 8 } + } + + fun foldList(): Int { + return numbers.fold(100) { total, it -> + println("total = $total, it = $it") + total - it + } // ((((100 - 1)-15)-3)-8) = 73 + } + + fun foldRightList(): Int { + return numbers.foldRight(100) { it, total -> + println("total = $total, it = $it") + total - it + } // ((((100-8)-3)-15)-1) = 73 + } + + fun foldIndexedList(): Int { + return numbers.foldIndexed(100) { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((100 - 3)-8) = 89 + } + + fun foldRightIndexedList(): Int { + return numbers.foldRightIndexed(100) { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((100 - 8)-3) = 89 + } + + fun reduceList(): Int { + return numbers.reduce { total, it -> + println("total = $total, it = $it") + total - it + } // (((1 - 15)-3)-8) = -25 + } + + fun reduceRightList(): Int { + return numbers.reduceRight() { it, total -> + println("total = $total, it = $it") + total - it + } // ((8-3)-15)-1) = -11 + } + + fun reduceIndexedList(): Int { + return numbers.reduceIndexed { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((1-3)-8) = -10 + } + + fun reduceRightIndexedList(): Int { + return numbers.reduceRightIndexed { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((8-3) = 5 + } +} diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt new file mode 100644 index 0000000000..a619759b0a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt @@ -0,0 +1,104 @@ +package com.baeldung.aggregate + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class AggregateOperationsUnitTest { + + private val classUnderTest: AggregateOperations = AggregateOperations() + + @Test + fun whenCountOfList_thenReturnsValue() { + assertEquals(4, classUnderTest.countList()) + } + + @Test + fun whenSumOfList_thenReturnsTotalValue() { + assertEquals(27, classUnderTest.sumList()) + } + + @Test + fun whenAverageOfList_thenReturnsValue() { + assertEquals(6.75, classUnderTest.averageList()) + } + + @Test + fun whenMaximumOfList_thenReturnsMaximumValue() { + assertEquals(15, classUnderTest.maximumInList()) + } + + @Test + fun whenMinimumOfList_thenReturnsMinimumValue() { + assertEquals(1, classUnderTest.minimumInList()) + } + + @Test + fun whenMaxByList_thenReturnsLargestValue() { + assertEquals(3, classUnderTest.maximumByList()) + } + + @Test + fun whenMinByList_thenReturnsSmallestValue() { + assertEquals(15, classUnderTest.minimumByList()) + } + + @Test + fun whenMaxWithList_thenReturnsLargestValue(){ + assertEquals("Kolkata", classUnderTest.maximumWithList()) + } + + @Test + fun whenMinWithList_thenReturnsSmallestValue(){ + assertEquals("Barcelona", classUnderTest.minimumWithList()) + } + + @Test + fun whenSumByList_thenReturnsIntegerValue(){ + assertEquals(135, classUnderTest.sumByList()) + } + + @Test + fun whenSumByDoubleList_thenReturnsDoubleValue(){ + assertEquals(3.375, classUnderTest.sumByDoubleList()) + } + + @Test + fun whenFoldList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldList()) + } + + @Test + fun whenFoldRightList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldRightList()) + } + + @Test + fun whenFoldIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldIndexedList()) + } + + @Test + fun whenFoldRightIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldRightIndexedList()) + } + + @Test + fun whenReduceList_thenReturnsValue(){ + assertEquals(-25, classUnderTest.reduceList()) + } + + @Test + fun whenReduceRightList_thenReturnsValue(){ + assertEquals(-11, classUnderTest.reduceRightList()) + } + + @Test + fun whenReduceIndexedList_thenReturnsValue(){ + assertEquals(-10, classUnderTest.reduceIndexedList()) + } + + @Test + fun whenReduceRightIndexedList_thenReturnsValue(){ + assertEquals(5, classUnderTest.reduceRightIndexedList()) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 8b626e1c1b..67520a7dee 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -21,6 +21,7 @@ core-kotlin-advanced core-kotlin-annotations core-kotlin-collections + core-kotlin-collections-2 core-kotlin-concurrency core-kotlin-date-time core-kotlin-design-patterns diff --git a/docker/docker-spring-boot/README.md b/docker/docker-spring-boot/README.md deleted file mode 100644 index 78f13a3652..0000000000 --- a/docker/docker-spring-boot/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Article: - -- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images) diff --git a/drools/README.MD b/drools/README.MD index 414ad2dea3..6011c8293c 100644 --- a/drools/README.MD +++ b/drools/README.MD @@ -6,3 +6,4 @@ This module contains articles about Drools - [Introduction to Drools](https://www.baeldung.com/drools) - [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining) +- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) diff --git a/gradle-5/settings.gradle b/gradle-5/settings.gradle index 1997e12ca5..5384d071e7 100644 --- a/gradle-5/settings.gradle +++ b/gradle-5/settings.gradle @@ -1,3 +1,4 @@ rootProject.name='gradle-5-articles' include 'java-exec' -include 'unused-dependencies' \ No newline at end of file +include 'unused-dependencies' +include 'source-sets' \ No newline at end of file diff --git a/gradle-5/source-sets/.gitignore b/gradle-5/source-sets/.gitignore new file mode 100644 index 0000000000..84c048a73c --- /dev/null +++ b/gradle-5/source-sets/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle new file mode 100644 index 0000000000..8325450cfd --- /dev/null +++ b/gradle-5/source-sets/build.gradle @@ -0,0 +1,67 @@ + +apply plugin: "eclipse" +apply plugin: "java" + +description = "Source Sets example" + +task printSourceSetInformation(){ + description = "Print source set information" + + doLast{ + sourceSets.each { srcSet -> + println "["+srcSet.name+"]" + print "-->Source directories: "+srcSet.allJava.srcDirs+"\n" + print "-->Output directories: "+srcSet.output.classesDirs.files+"\n" + print "-->Compile classpath:\n" + srcSet.compileClasspath.files.each { + print " "+it.path+"\n" + } + println "" + } + } +} + +sourceSets{ + itest { + compileClasspath += sourceSets.main.output + runtimeClasspath += sourceSets.main.output + java { + } + } +} + +test { + testLogging { + events "passed","skipped", "failed" + } +} + +dependencies { + implementation('org.apache.httpcomponents:httpclient:4.5.12') + testImplementation('junit:junit:4.12') + itestImplementation('com.google.guava:guava:29.0-jre') +} + +task itest(type: Test) { + description = "Run integration tests" + group = "verification" + testClassesDirs = sourceSets.itest.output.classesDirs + classpath = sourceSets.itest.runtimeClasspath +} + +itest { + testLogging { + events "passed","skipped", "failed" + } +} + +configurations { + itestImplementation.extendsFrom(testImplementation) + itestRuntimeOnly.extendsFrom(testRuntimeOnly) +} + +eclipse { + classpath { + plusConfigurations+=[configurations.itestCompileClasspath] + } +} \ No newline at end of file diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java new file mode 100644 index 0000000000..3312c5b6e5 --- /dev/null +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -0,0 +1,25 @@ +package com.baeldung.itest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +import com.baeldung.main.SourceSetsObject; +import com.google.common.collect.ImmutableList; + +public class SourceSetsItest { + + @Test + public void givenImmutableList_whenRun_ThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); + assertThat(someStrings.size(), is(3)); + } +} diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java new file mode 100644 index 0000000000..319894d336 --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java @@ -0,0 +1,9 @@ +package com.baeldung.main; + +public class SourceSetsMain { + + public static void main(String[] args) { + System.out.println("Hell..oh...world!"); + } + +} diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java new file mode 100644 index 0000000000..130121789c --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java @@ -0,0 +1,21 @@ +package com.baeldung.main; + +public class SourceSetsObject { + + private final String user; + private final String password; + + public SourceSetsObject(String user, String password) { + this.user = user; + this.password = password; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + +} diff --git a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java new file mode 100644 index 0000000000..b033eb8e52 --- /dev/null +++ b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java @@ -0,0 +1,20 @@ +package com.baeldung.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +import com.baeldung.main.SourceSetsObject; + +public class SourceSetsTest { + + @Test + public void whenRun_ThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); + } +} diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index c965fd962d..dbc46bbb97 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -237,6 +237,26 @@ spring-boot:run + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + + set-system-properties + + + + + org.slf4j.simpleLogger.log.com.github.eirslett + error + + + + + + org.apache.maven.plugins maven-compiler-plugin diff --git a/jhipster/pom.xml b/jhipster/pom.xml index dd16205706..1703e82e0e 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -9,6 +9,8 @@ pom + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index e02f766141..202b3b8763 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -14,29 +14,24 @@ - org.springframework.boot spring-boot-starter-web - org.springframework.security.oauth spring-security-oauth2 ${spring-boot.version} - org.springframework spring-web - com.github.scribejava scribejava-apis ${scribejava.version} - com.google.crypto.tink tink @@ -72,6 +67,16 @@ jasypt ${jasypt.version} + + com.jcraft + jsch + ${jsch.version} + + + org.apache.sshd + sshd-core + ${apache-mina.version} + @@ -81,6 +86,8 @@ 1.2.2 1.9.2 1.58 + 0.1.55 + 2.5.1 diff --git a/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java new file mode 100644 index 0000000000..05d8034040 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java @@ -0,0 +1,64 @@ +package com.baeldung.ssh.apachesshd; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.EnumSet; +import java.util.concurrent.TimeUnit; + +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.channel.ClientChannel; +import org.apache.sshd.client.channel.ClientChannelEvent; +import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.channel.Channel; + +public class SshdDemo { + + public static void main(String[] args) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + + listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception { + SshClient client = SshClient.setUpDefaultClient(); + client.start(); + try (ClientSession session = client.connect(username, host, port) + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS) + .getSession()) { + session.addPasswordIdentity(password); + session.auth() + .verify(5L, TimeUnit.SECONDS); + try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) { + channel.setOut(responseStream); + channel.setErr(errorResponseStream); + try { + channel.open() + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); + try (OutputStream pipedIn = channel.getInvertedIn()) { + pipedIn.write(command.getBytes()); + pipedIn.flush(); + } + channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds)); + String errorString = new String(errorResponseStream.toByteArray()); + if(!errorString.isEmpty()) { + throw new Exception(errorString); + } + String responseString = new String(responseStream.toByteArray()); + return responseString; + } finally { + channel.close(false); + } + } + } finally { + client.stop(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java new file mode 100644 index 0000000000..34a40318bb --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java @@ -0,0 +1,52 @@ +package com.baeldung.ssh.jsch; + +import java.io.ByteArrayOutputStream; + +import com.jcraft.jsch.ChannelExec; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; + +public class JschDemo { + + public static void main(String args[]) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + listFolderStructure(username, password, host, port, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception { + Session session = null; + ChannelExec channel = null; + String response = null; + try { + session = new JSch().getSession(username, host, port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(); + channel = (ChannelExec) session.openChannel("exec"); + channel.setCommand(command); + ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + channel.setOutputStream(responseStream); + channel.setErrStream(errorResponseStream); + channel.connect(); + while (channel.isConnected()) { + Thread.sleep(100); + } + String errorResponse = new String(errorResponseStream.toByteArray()); + response = new String(responseStream.toByteArray()); + if(!errorResponse.isEmpty()) { + throw new Exception(errorResponse); + } + } finally { + if (session != null) + session.disconnect(); + if (channel != null) + channel.disconnect(); + } + return response; + } +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java new file mode 100644 index 0000000000..3cefca05cb --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java @@ -0,0 +1,38 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.apachesshd.SshdDemo; + +public class ApacheMinaSshdLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNull(responseString); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java new file mode 100644 index 0000000000..c95c3c319c --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.jsch.JschDemo; + +public class JSchLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNull(responseString); + } +} diff --git a/logging-modules/log-mdc/Dockerfile b/logging-modules/log-mdc/Dockerfile new file mode 100644 index 0000000000..e69de29bb2 diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index 0d516619ef..f35bc7fccc 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,8 +1,6 @@ ### Relevant Articles: -- TBD - [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) - [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) -- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index e367a63de6..bc4800ea37 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 diff --git a/open-liberty/pom.xml b/open-liberty/pom.xml index d6588ce49a..0e8b159043 100644 --- a/open-liberty/pom.xml +++ b/open-liberty/pom.xml @@ -27,6 +27,7 @@ org.apache.derby derby ${version.derby} + provided @@ -70,27 +71,16 @@ io.openliberty.tools liberty-maven-plugin ${version.liberty-maven-plugin} - - - org.apache.maven.plugins - maven-dependency-plugin - ${version.maven-dependency-plugin} - - - copy-derby-dependency - package - - copy-dependencies - - - derby - ${project.build.directory}/liberty/wlp/usr/shared/resources/ - - ${testServerHttpPort} - - - - + + + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + org.apache.derby + derby + ${version.derby} + + + org.apache.maven.plugins @@ -112,8 +102,7 @@ 8.0.0 3.2 10.14.2.0 - 3.1 - 2.10 + 3.3-M3 3.2.3 4.12 1.0.5 diff --git a/persistence-modules/hibernate-ogm/src/test/resources/logback.xml b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java index 3fe858936a..8cfee8f5d6 100644 --- a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java +++ b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java @@ -44,7 +44,7 @@ public class EqualByBusinessKey { return false; } if (obj instanceof EqualByBusinessKey) { - if (((EqualByBusinessKey) obj).getEmail() == getEmail()) { + if (((EqualByBusinessKey) obj).getEmail().equals(getEmail())) { return true; } } diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties index c22da2496b..4999a0e600 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties @@ -5,6 +5,6 @@ hibernate.connection.autocommit=true jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java index bdfb8e890f..d824505629 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java @@ -1,14 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "course") public class Course { @@ -18,31 +13,55 @@ public class Course { private Long id; @ManyToMany(mappedBy = "likedCourses") - private Set likes; + private Set likes = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Course() { } + public Course(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + + public Set getLikes() { + return likes; + } + + public void setLikes(Set likes) { + this.likes = likes; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java index 4951f766bc..b89cc1dae9 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java @@ -1,12 +1,6 @@ package com.baeldung.manytomany.model; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(name = "course_rating") @@ -16,12 +10,12 @@ public class CourseRating { private CourseRatingKey id; @ManyToOne - @MapsId("student_id") + @MapsId("studentId") @JoinColumn(name = "student_id") private Student student; @ManyToOne - @MapsId("course_id") + @MapsId("courseId") @JoinColumn(name = "course_id") private Course course; @@ -31,26 +25,38 @@ public class CourseRating { public CourseRating() { } - public int getRating() { - return rating; - } - - public void setRating(int rating) { - this.rating = rating; - } - public CourseRatingKey getId() { return id; } + public void setId(CourseRatingKey id) { + this.id = id; + } + public Student getStudent() { return student; } + public void setStudent(Student student) { + this.student = student; + } + public Course getCourse() { return course; } + public void setCourse(Course course) { + this.course = course; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java index 4e7430ed92..a4b2df9b07 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java @@ -1,9 +1,8 @@ package com.baeldung.manytomany.model; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Embeddable; +import java.io.Serializable; @Embeddable public class CourseRatingKey implements Serializable { @@ -17,14 +16,27 @@ public class CourseRatingKey implements Serializable { public CourseRatingKey() { } + public CourseRatingKey(Long studentId, Long courseId) { + this.studentId = studentId; + this.courseId = courseId; + } + public Long getStudentId() { return studentId; } + public void setStudentId(Long studentId) { + this.studentId = studentId; + } + public Long getCourseId() { return courseId; } + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java index e1f30af883..ba914b564d 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java @@ -1,14 +1,8 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; import java.time.LocalDateTime; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - @Entity @Table(name = "course_registration") public class CourseRegistration { @@ -36,6 +30,14 @@ public class CourseRegistration { public CourseRegistration() { } + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + public Student getStudent() { return student; } @@ -68,10 +70,6 @@ public class CourseRegistration { this.grade = grade; } - public Long getId() { - return id; - } - @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java index 00561593a6..53c5d88a57 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java @@ -1,16 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "student") public class Student { @@ -21,35 +14,55 @@ public class Student { @ManyToMany @JoinTable(name = "course_like", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) - private Set likedCourses; + private Set likedCourses = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Student() { } + public Student(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + public Set getLikedCourses() { return likedCourses; } + public void setLikedCourses(Set likedCourses) { + this.likedCourses = likedCourses; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java index 5e4334f5d4..f5b02ec2c1 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java @@ -1,17 +1,27 @@ package com.baeldung.manytomany; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - +import com.baeldung.manytomany.model.Course; +import com.baeldung.manytomany.model.CourseRating; +import com.baeldung.manytomany.model.CourseRatingKey; +import com.baeldung.manytomany.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) @ContextConfiguration(classes = ManyToManyTestConfiguration.class) @DirtiesContext +@Transactional public class ManyToManyIntegrationTest { @PersistenceContext @@ -21,4 +31,25 @@ public class ManyToManyIntegrationTest { public void contextStarted() { } + @Test + public void whenCourseRatingPersisted_thenCorrect() { + Student student = new Student(101L); + entityManager.persist(student); + + Course course = new Course(201L); + entityManager.persist(course); + + CourseRating courseRating = new CourseRating(); + courseRating.setId(new CourseRatingKey()); + courseRating.setStudent(student); + courseRating.setCourse(course); + courseRating.setRating(100); + entityManager.persist(courseRating); + + CourseRating persistedCourseRating = entityManager.find(CourseRating.class, new CourseRatingKey(101L, 201L)); + + assertThat(persistedCourseRating, notNullValue()); + assertThat(persistedCourseRating.getStudent().getId(), is(101L)); + assertThat(persistedCourseRating.getCourse().getId(), is(201L)); + } } diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java index 1cc3621f0d..fa12828074 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java @@ -1,20 +1,21 @@ package com.baeldung.manytomany; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + @Configuration @PropertySource("manytomany/test.properties") public class ManyToManyTestConfiguration { @@ -23,8 +24,8 @@ public class ManyToManyTestConfiguration { public DataSource dataSource() { EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); return dbBuilder.setType(EmbeddedDatabaseType.H2) - .addScript("classpath:/manytomany/db.sql") - .build(); + .addScript("classpath:/manytomany/db.sql") + .build(); } @Bean @@ -44,6 +45,13 @@ public class ManyToManyTestConfiguration { return result; } + @Bean + JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + public JpaVendorAdapter jpaVendorAdapter() { return new HibernateJpaVendorAdapter(); } diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 09eb90d110..67356abdef 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -30,9 +30,48 @@ io.quarkus quarkus-resteasy + + io.quarkus + quarkus-resteasy-jackson + ${quarkus.version} + + + io.quarkus + quarkus-hibernate-orm-panache + ${quarkus.version} + + + io.quarkus + quarkus-jdbc-h2 + ${quarkus.version} + + + org.apache.commons + commons-lang3 + 3.9 + + + org.projectlombok + lombok + 1.18.6 + provided + io.quarkus quarkus-junit5 + ${quarkus.version} + test + + + io.quarkus + quarkus-junit5-mockito + ${quarkus.version} + test + + + io.quarkus + quarkus-test-h2 + ${quarkus.version} test @@ -117,7 +156,8 @@ 2.22.0 - 0.15.0 + 1.7.0.Final + 5.6.0 diff --git a/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java new file mode 100644 index 0000000000..88c3f0ed6e --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java @@ -0,0 +1,25 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.service.LibraryService; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Set; + +@Path("/library") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LibraryResource { + + @Inject + LibraryService libraryService; + + @GET + @Path("/book") + public Set findBooks(@QueryParam("query") String query) { + return libraryService.find(query); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java new file mode 100644 index 0000000000..7d258c1934 --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java @@ -0,0 +1,17 @@ +package com.baeldung.quarkus.model; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; +import lombok.*; + +import javax.persistence.Entity; + +@Data +@Entity +@AllArgsConstructor +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Book extends PanacheEntity { + private String title; + private String author; +} + diff --git a/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java new file mode 100644 index 0000000000..b142fa569b --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.model.Book; +import io.quarkus.hibernate.orm.panache.PanacheRepository; + +import javax.enterprise.context.ApplicationScoped; +import java.util.stream.Stream; + +import static io.quarkus.panache.common.Parameters.with; + +@ApplicationScoped +public class BookRepository implements PanacheRepository { + + public Stream findBy(String query) { + return find("author like :query or title like :query", with("query", "%"+query+"%")).stream(); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java new file mode 100644 index 0000000000..be687589bf --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java @@ -0,0 +1,28 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; +import java.util.Set; + +import static java.util.stream.Collectors.toSet; + +@Transactional +@ApplicationScoped +public class LibraryService { + + @Inject + BookRepository bookRepository; + + public Set find(String query) { + if (query == null) { + return bookRepository.findAll().stream().collect(toSet()); + } + + return bookRepository.findBy(query).collect(toSet()); + } + +} diff --git a/quarkus/src/main/resources/application.properties b/quarkus/src/main/resources/application.properties index 3f05d2198f..283cf763b9 100644 --- a/quarkus/src/main/resources/application.properties +++ b/quarkus/src/main/resources/application.properties @@ -1,3 +1,12 @@ # Configuration file # key = value -greeting=Good morning \ No newline at end of file +greeting=Good morning + +quarkus.datasource.db-kind = h2 +quarkus.datasource.jdbc.url = jdbc:h2:tcp://localhost/mem:test + +quarkus.hibernate-orm.database.generation = drop-and-create + +%custom-profile.quarkus.datasource.jdbc.url = jdbc:h2:file:./testdb + +quarkus.http.test-port=0 diff --git a/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java new file mode 100644 index 0000000000..b9175ae457 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.utils.CustomTestProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItems; + +@QuarkusTest +@TestProfile(CustomTestProfile.class) +class CustomLibraryResourceManualTest { + + public static final String BOOKSTORE_ENDPOINT = "/custom/library/book"; + + @Test + void whenGetBooksGivenNoQuery_thenAllBooksShouldBeReturned() { + given().contentType(ContentType.JSON) + .when().get(BOOKSTORE_ENDPOINT) + .then().statusCode(200) + .body("size()", is(2)) + .body("title", hasItems("Foundation", "Dune")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java new file mode 100644 index 0000000000..f3a30a2383 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; + +@QuarkusTest +@TestHTTPEndpoint(LibraryResource.class) +class LibraryHttpEndpointIntegrationTest { + + @Test + void whenGetBooks_thenShouldReturnSuccessfully() { + given().contentType(ContentType.JSON) + .when().get("book") + .then().statusCode(200); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java new file mode 100644 index 0000000000..1931460aaa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.URL; + +import static io.restassured.RestAssured.given; +import static java.nio.charset.Charset.defaultCharset; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class LibraryResourceHttpResourceIntegrationTest { + + @TestHTTPEndpoint(LibraryResource.class) + @TestHTTPResource("book") + URL libraryEndpoint; + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get(libraryEndpoint) + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + + @Test + void whenGetBooks_thenBooksShouldBeFound() throws IOException { + assertTrue(IOUtils.toString(libraryEndpoint.openStream(), defaultCharset()).contains("Asimov")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java new file mode 100644 index 0000000000..48ec1786fa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.service.LibraryService; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.verify; + +@QuarkusTest +class LibraryResourceInjectSpyIntegrationTest { + + @InjectSpy + LibraryService libraryService; + + @Test + void whenGetBooksByAuthor_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Asimov") + .when().get("/library/book") + .then().statusCode(200); + + verify(libraryService).find("Asimov"); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java new file mode 100644 index 0000000000..28eba8da44 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; + +@QuarkusTest +class LibraryResourceIntegrationTest { + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get("/library/book") + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java index 9ada64b6a5..e6c8a3b8fb 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java @@ -1,8 +1,11 @@ package com.baeldung.quarkus; -import io.quarkus.test.junit.SubstrateTest; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; -@SubstrateTest +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) public class NativeHelloResourceIT extends HelloResourceUnitTest { // Execute the same tests but in native mode. diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java new file mode 100644 index 0000000000..0c11fa6fb4 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java @@ -0,0 +1,10 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; + +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) +class NativeLibraryResourceIT extends LibraryHttpEndpointIntegrationTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..7d811b2268 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.utils.QuarkusTransactionalTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTransactionalTest +class BookRepositoryIntegrationTest { + + @Inject + BookRepository bookRepository; + + @Test + void givenBookInRepository_whenFindByAuthor_thenShouldReturnBookFromRepository() { + assertTrue(bookRepository.findBy("Herbert").findAny().isPresent()); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java new file mode 100644 index 0000000000..f0b7260c7d --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectMock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +@QuarkusTest +class LibraryServiceInjectMockUnitTest { + + @Inject + LibraryService libraryService; + + @InjectMock + BookRepository bookRepository; + + @BeforeEach + void setUp() { + when(bookRepository.findBy("Frank Herbert")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Dune", "Frank Herbert"), + new Book("Children of Dune", "Frank Herbert")})); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Frank Herbert").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java new file mode 100644 index 0000000000..16cce4d726 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus.service; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +@QuarkusTest +class LibraryServiceIntegrationTest { + + @Inject + LibraryService libraryService; + + @Test + void whenFindByAuthor_thenBookShouldBeFound() { + assertFalse(libraryService.find("Frank Herbert").isEmpty()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java new file mode 100644 index 0000000000..e2d40a0a0b --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import com.baeldung.quarkus.utils.TestBookRepository; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class LibraryServiceQuarkusMockUnitTest { + + @Inject + LibraryService libraryService; + + @BeforeEach + void setUp() { + BookRepository mock = Mockito.mock(TestBookRepository.class); + Mockito.when(mock.findBy("Asimov")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Foundation", "Isaac Asimov"), + new Book("I Robot", "Isaac Asimov")})); + QuarkusMock.installMockForType(mock, BookRepository.class); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Asimov").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java new file mode 100644 index 0000000000..75fb736acc --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java @@ -0,0 +1,26 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +public class CustomTestProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Collections.singletonMap("quarkus.resteasy.path", "/custom"); + } + + @Override + public Set> getEnabledAlternatives() { + return Collections.singleton(TestBookRepository.class); + } + + @Override + public String getConfigProfile() { + return "custom-profile"; + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java new file mode 100644 index 0000000000..d02cff2662 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTest; + +import javax.enterprise.inject.Stereotype; +import javax.transaction.Transactional; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@QuarkusTest +@Stereotype +@Transactional +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface QuarkusTransactionalTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java new file mode 100644 index 0000000000..baaa9fd005 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.quarkus.utils; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.annotation.PostConstruct; +import javax.annotation.Priority; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +@Priority(1) +@Alternative +@ApplicationScoped +public class TestBookRepository extends BookRepository { + + @PostConstruct + public void init() { + persist(new Book("Dune", "Frank Herbert"), + new Book("Foundation", "Isaac Asimov")); + } + +} diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index c9917d14df..317cbde6e2 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -34,7 +34,7 @@ - 3.2.6.RELEASE + 3.3.9.RELEASE 3.6.1 diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java similarity index 91% rename from reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java rename to reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java index e3060b8e02..a1acffac91 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactor; +package com.baeldung.reactor.introduction; import org.junit.Test; import org.reactivestreams.Subscriber; @@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ReactorIntegrationTest { @Test - public void givenFlux_whenSubscribing_thenStream() throws InterruptedException { + public void givenFlux_whenSubscribing_thenStream() { List elements = new ArrayList<>(); @@ -48,14 +48,12 @@ public class ReactorIntegrationTest { } @Test - public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() throws InterruptedException { + public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() { List elements = new ArrayList<>(); Flux.just(1, 2, 3, 4) .log() - .map(i -> i * 2) - .onBackpressureBuffer() .subscribe(new Subscriber() { private Subscription s; int onNextAmount; @@ -81,11 +79,10 @@ public class ReactorIntegrationTest { @Override public void onComplete() { - int ham = 2; } }); - assertThat(elements).containsExactly(2, 4, 6, 8); + assertThat(elements).containsExactly(1, 2, 3, 4); } @Test diff --git a/spring-4/pom.xml b/spring-4/pom.xml index b6b8deb273..cd6b232317 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -8,6 +8,7 @@ jar + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 4803827b45..a8557b4f56 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -8,6 +8,7 @@ Demo project for Spring Boot + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index b4cabaaedf..109be01db3 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -61,6 +61,7 @@ spring-boot-runtime spring-boot-security spring-boot-springdoc + spring-boot-swagger spring-boot-testing spring-boot-vue spring-boot-xml diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml index 145bb221e0..d44120b21e 100644 --- a/spring-boot-modules/spring-boot-1/pom.xml +++ b/spring-boot-modules/spring-boot-1/pom.xml @@ -7,6 +7,7 @@ Module for Spring Boot version 1.x + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-actuator/README.MD b/spring-boot-modules/spring-boot-actuator/README.md similarity index 72% rename from spring-boot-modules/spring-boot-actuator/README.MD rename to spring-boot-modules/spring-boot-actuator/README.md index fbb4dfba0f..6f31ee4a5e 100644 --- a/spring-boot-modules/spring-boot-actuator/README.MD +++ b/spring-boot-modules/spring-boot-actuator/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Liveness and Readiness Probes in Spring Boot](https://www.baeldung.com/spring-liveness-readiness-probes) +- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml index 701949519e..18da6d3a9a 100644 --- a/spring-boot-modules/spring-boot-actuator/pom.xml +++ b/spring-boot-modules/spring-boot-actuator/pom.xml @@ -24,6 +24,14 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java new file mode 100644 index 0000000000..75a7182b3c --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.endpoints.info; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index c316cabda5..a685660b4f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -3,7 +3,6 @@ package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java new file mode 100644 index 0000000000..db4e69127a --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java @@ -0,0 +1,49 @@ +package com.baeldung.endpoints.info; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer status; + + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + + 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; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java new file mode 100644 index 0000000000..8af5ef3988 --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java @@ -0,0 +1,78 @@ +package com.baeldung.endpoints.info; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + + int countByStatus(int status); + + Optional findOneByName(String name); + + @Async + CompletableFuture findOneByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties index 27dba985b8..00100d6d97 100644 --- a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties @@ -2,4 +2,10 @@ management.health.probes.enabled=true management.endpoint.health.show-details=always management.endpoint.health.status.http-mapping.down=500 management.endpoint.health.status.http-mapping.out_of_service=503 -management.endpoint.health.status.http-mapping.warning=500 \ No newline at end of file +management.endpoint.health.status.http-mapping.warning=500 + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 +info.java-vendor = ${java.specification.vendor} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java new file mode 100644 index 0000000000..977de5534d --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.conditionalonproperty; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NotificationApplication { + + public static void main(String[] args) { + SpringApplication.run(NotificationApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java new file mode 100644 index 0000000000..ffd942cd02 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.conditionalonproperty.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; +import com.baeldung.conditionalonproperty.service.SmsNotification; + +@Configuration +public class NotificationConfig { + + @Bean(name = "emailNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "email") + public NotificationSender notificationSender() { + return new EmailNotification(); + } + + @Bean(name = "smsNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms") + public NotificationSender notificationSender2() { + return new SmsNotification(); + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java new file mode 100644 index 0000000000..c66800f817 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class EmailNotification implements NotificationSender { + + @Override + public String send(String message) { + return "Email Notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java new file mode 100644 index 0000000000..945306e7c4 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java @@ -0,0 +1,5 @@ +package com.baeldung.conditionalonproperty.service; + +public interface NotificationSender { + String send(String message); +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java new file mode 100644 index 0000000000..dcf611da19 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class SmsNotification implements NotificationSender { + + @Override + public String send(String message) { + return "SMS notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties index 4456c78e5d..03f753abf9 100644 --- a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties @@ -1,2 +1,4 @@ spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto = update + +notification.service=email diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java new file mode 100644 index 0000000000..fb9b177e5f --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.conditionalonproperty; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import com.baeldung.conditionalonproperty.config.NotificationConfig; +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; + +public class NotificationUnitTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenValueSetToEmail_thenCreateEmailNotification() { + this.contextRunner.withPropertyValues("notification.service=email") + .withUserConfiguration(NotificationConfig.class) + .run(context -> { + assertThat(context).hasBean("emailNotification"); + NotificationSender notificationSender = context.getBean(EmailNotification.class); + assertThat(notificationSender.send("Hello From Baeldung!")).isEqualTo("Email Notification: Hello From Baeldung!"); + assertThat(context).doesNotHaveBean("smsNotification"); + }); + } +} diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml index 881b021b96..46a90b4722 100644 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -38,12 +38,10 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot-starter.version} org.springframework.boot spring-boot-starter-test - ${spring-boot-starter.version} test @@ -55,7 +53,6 @@ org.springframework.boot spring-boot-maven-plugin - ${spring-boot-starter.version} @@ -68,8 +65,7 @@ - 2.19.1 - 1.5.4.RELEASE + 3.0.0-M4 diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java index aadd37a3b4..48294e9c56 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java +++ b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java @@ -12,33 +12,36 @@ import org.apache.camel.model.rest.RestBindingMode; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration; +import org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; -@SpringBootApplication -@ComponentScan(basePackages="com.baeldung.camel") -public class Application{ +@SpringBootApplication(exclude = { WebSocketServletAutoConfiguration.class, AopAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, EmbeddedWebServerFactoryCustomizerAutoConfiguration.class }) +@ComponentScan(basePackages = "com.baeldung.camel") +public class Application { @Value("${server.port}") String serverPort; - + @Value("${baeldung.api.path}") String contextPath; - + public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean ServletRegistrationBean servletRegistrationBean() { - ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*"); + ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*"); servlet.setName("CamelServlet"); return servlet; } - @Component class RestApi extends RouteBuilder { @@ -47,7 +50,6 @@ public class Application{ CamelContext context = new DefaultCamelContext(); - // http://localhost:8080/camel/api-doc restConfiguration().contextPath(contextPath) // .port(serverPort) @@ -60,43 +62,43 @@ public class Application{ .component("servlet") .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); -/** -The Rest DSL supports automatic binding json/xml contents to/from -POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic -binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to -your REST services request and response types. -*/ - + /** + The Rest DSL supports automatic binding json/xml contents to/from + POJOs using Camels Data Format. + By default the binding mode is off, meaning there is no automatic + binding happening for incoming and outgoing messages. + You may want to use binding if you develop POJOs that maps to + your REST services request and response types. + */ + rest("/api/").description("Teste REST Service") .id("api-route") .post("/bean") .produces(MediaType.APPLICATION_JSON) .consumes(MediaType.APPLICATION_JSON) -// .get("/hello/{place}") + // .get("/hello/{place}") .bindingMode(RestBindingMode.auto) .type(MyBean.class) .enableCORS(true) -// .outType(OutBean.class) + // .outType(OutBean.class) .to("direct:remoteService"); - - - from("direct:remoteService") - .routeId("direct-route") + + from("direct:remoteService").routeId("direct-route") .tracing() .log(">>> ${body.id}") .log(">>> ${body.name}") -// .transform().simple("blue ${in.body.name}") + // .transform().simple("blue ${in.body.name}") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { - MyBean bodyIn = (MyBean) exchange.getIn().getBody(); - + MyBean bodyIn = (MyBean) exchange.getIn() + .getBody(); + ExampleServices.example(bodyIn); - exchange.getIn().setBody(bodyIn); + exchange.getIn() + .setBody(bodyIn); } }) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties index bce95f8eaf..29fee8cff6 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties @@ -12,4 +12,6 @@ management.port=8081 # disable all management enpoints except health endpoints.enabled = true -endpoints.health.enabled = true \ No newline at end of file +endpoints.health.enabled = true + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-di/README.MD b/spring-boot-modules/spring-boot-di/README.md similarity index 81% rename from spring-boot-modules/spring-boot-di/README.MD rename to spring-boot-modules/spring-boot-di/README.md index cbd42c5609..2759c73926 100644 --- a/spring-boot-modules/spring-boot-di/README.MD +++ b/spring-boot-modules/spring-boot-di/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Spring @ComponentScan – Filter Types](https://www.baeldung.com/spring-componentscan-filter-type) +- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) diff --git a/spring-boot-modules/spring-boot-di/pom.xml b/spring-boot-modules/spring-boot-di/pom.xml index 87a0ad2937..58b427a4a8 100644 --- a/spring-boot-modules/spring-boot-di/pom.xml +++ b/spring-boot-modules/spring-boot-di/pom.xml @@ -27,6 +27,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + org.springframework.boot spring-boot-starter-tomcat diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java rename to spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md index 8cd3db9c93..10c56ca576 100644 --- a/spring-boot-modules/spring-boot-libraries/README.md +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -12,3 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) - [Rate Limiting a Spring API Using Bucket4j](https://www.baeldung.com/spring-bucket4j) - [Spring Boot and Caffeine Cache](https://www.baeldung.com/spring-boot-caffeine-cache) +- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) +- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) +- [An Introduction to Kong](https://www.baeldung.com/kong) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 05ab59aab7..3913babaa8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -37,6 +37,36 @@ spring-boot-starter-test test + + + + org.togglz + togglz-spring-boot-starter + ${togglz.version} + + + + org.togglz + togglz-spring-security + ${togglz.version} + + + + + com.graphql-java + graphql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + com.graphql-java + graphql-java-tools + ${graphql-java-tools.version} + + + com.graphql-java + graphiql-spring-boot-starter + ${graphql-spring-boot-starter.version} + @@ -216,7 +246,6 @@ 1.9.0 2.0.0 5.0.2 - 5.0.2 5.2.4 18.0 2.2.4 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java new file mode 100644 index 0000000000..eb091b4695 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.demo; + +import com.baeldung.graphql.GraphqlConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(GraphqlConfiguration.class) +public class DemoApplication { + + public static void main(String[] args) { + System.setProperty("spring.config.name", "demo"); + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java new file mode 100644 index 0000000000..64a8b3ce5b --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java @@ -0,0 +1,37 @@ +package com.baeldung.toggle; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 41b98063a6..5e9ecded10 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -9,4 +9,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) - [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) +- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) +- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 9ae6d8341a..39046ee6d9 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -49,6 +49,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-data-rest + mysql @@ -99,24 +103,7 @@ io.springfox - springfox-swagger2 - ${spring.fox.version} - - - io.springfox - springfox-swagger-ui - ${spring.fox.version} - - - - io.springfox - springfox-data-rest - ${spring.fox.version} - - - - io.springfox - springfox-bean-validators + springfox-boot-starter ${spring.fox.version} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java similarity index 87% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java index 96a534b853..efa55b8b33 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java @@ -8,7 +8,7 @@ public class PageController { @GetMapping("/international") public String getInternationalPage() { - return "international"; + return "thymeleaf/international"; } } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index 434a8d77cb..b404b0c2f8 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -1,13 +1,9 @@ package com.baeldung.swagger2boot.configuration; -import org.springframework.boot.autoconfigure.domain.EntityScan; +import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; - -import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; - import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; @@ -16,13 +12,16 @@ import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger.web.*; -import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; @Configuration -@EnableSwagger2WebMvc @Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SpringFoxConfig { @@ -43,8 +42,8 @@ public class SpringFoxConfig { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) .build(); } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties index 9794c89651..8f956fe5be 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties @@ -1 +1,5 @@ -email.notempty=Please provide valid email id. \ No newline at end of file +email.notempty=Please provide valid email id. +greeting=Hello! Welcome to our website! +lang.change=Change the language +lang.eng=English +lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties index 070f4e0bfc..7ced0d7b0d 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties @@ -1 +1,5 @@ -email.notempty=Veuillez fournir un identifiant de messagerie valide. \ No newline at end of file +email.notempty=Veuillez fournir un identifiant de messagerie valide. +greeting=Bonjour! Bienvenue sur notre site! +lang.change=Changez la langue +lang.eng=Anglais +lang.fr=Francais diff --git a/spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js b/spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js rename to spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/international.html b/spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/international.html rename to spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8c85934fac..92223892d9 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -1,23 +1,21 @@ package com.baeldung.annotation.servletcomponentscan; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) public class SpringBootWithServletComponentIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml index 7d900d8ea8..73dd672c1a 100644 --- a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml +++ b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/test/resources/application.properties b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties new file mode 100644 index 0000000000..5494069009 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties @@ -0,0 +1,2 @@ +logging.level.root=ERROR +logging.level.com.baeldung.integrationtesting=ERROR diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml new file mode 100644 index 0000000000..4e0180460d --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../ + + + spring-boot-swagger + 0.1.0-SNAPSHOT + spring-boot-swagger + jar + + Module For Spring Boot Swagger + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-boot-starter + 3.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java new file mode 100644 index 0000000000..911c29a4f6 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.swagger2boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSwaggerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSwaggerApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java new file mode 100644 index 0000000000..4f85d90f5f --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -0,0 +1,63 @@ +package com.baeldung.swagger2boot.configuration; + +import java.util.Collections; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; + +@Configuration +public class SwaggerConfiguration { + + private ApiInfo apiInfo() { + return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", + new Contact("Umang Budhwar", "www.baeldung.com", "umangbudhwar@gmail.com"), + "License of API", "API license URL", Collections.emptyList()); + } + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } + + /** + * SwaggerUI information + */ + + @Bean + UiConfiguration uiConfig() { + return UiConfigurationBuilder.builder() + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); + } + +} diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java new file mode 100644 index 0000000000..5218092c21 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java @@ -0,0 +1,35 @@ +package com.baeldung.swagger2boot.controller; + +import java.time.LocalDate; +import java.time.LocalTime; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.annotations.ApiOperation; +import springfox.documentation.annotations.ApiIgnore; + +@ApiIgnore +@RestController +public class RegularRestController { + + @ApiIgnore + @ApiOperation(value = "This method is used to get the author name.") + @GetMapping("/getAuthor") + public String getAuthor() { + return "Umang Budhwar"; + } + + @ApiOperation(value = "This method is used to get the current date.", hidden = true) + @GetMapping("/getDate") + public LocalDate getDate() { + return LocalDate.now(); + } + + @ApiOperation(value = "This method is used to get the current time.") + @GetMapping("/getTime") + public LocalTime getTime() { + return LocalTime.now(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties b/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 192f5cee99..1b7ad661c6 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -14,3 +14,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) - [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) +- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml index a3b176af88..bd5ef901dd 100644 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -34,6 +34,14 @@ org.springframework.boot spring-boot-starter-security + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java index fa3c1dc809..2921ecc609 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java index b6850d587e..bcef5231e0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java index 7d2e06d4a0..b52d38e028 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java index ff1976cad1..6fc48a3c3d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java index 156fc571f3..7d5ec4a05d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties index 8dc7f6e3c3..daab3e8d2c 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties @@ -4,4 +4,6 @@ spring.redis.port= 6379 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java index 962abf0fa3..c51113a023 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java @@ -1,19 +1,4 @@ -package com.baeldung.demo.boottest; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Arrays; -import java.util.List; +package com.baeldung.boot.testing; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; @@ -25,8 +10,28 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.internal.verification.VerificationModeFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRestController; +import com.baeldung.boot.testing.EmployeeService; + @RunWith(SpringRunner.class) -@WebMvcTest(EmployeeRestController.class) +@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) public class EmployeeControllerIntegrationTest { @Autowired diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java index 164887886b..b3a7316764 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,5 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +7,9 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + import java.util.List; import static org.assertj.core.api.Assertions.assertThat; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java index 327e9f9d56..d13fcd79aa 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,11 +14,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @@ -27,9 +28,14 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.boot.Application; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class) @AutoConfigureMockMvc +@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java index 88f2830a2b..3176a7c75a 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; @@ -6,10 +6,6 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; -import com.baeldung.demo.boottest.EmployeeService; -import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,6 +17,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; +import com.baeldung.boot.testing.EmployeeService; +import com.baeldung.boot.testing.EmployeeServiceImpl; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java similarity index 91% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java index 3fcd709f7c..49d018dde8 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties index 0c5b0e13e6..1810c7b1eb 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties @@ -3,4 +3,6 @@ spring.redis.host= localhost spring.redis.port= 6370 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.md similarity index 62% rename from spring-boot-modules/spring-boot/README.MD rename to spring-boot-modules/spring-boot/README.md index c95fe51842..5a45502fd8 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.md @@ -8,18 +8,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) -- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) -- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) -- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) -- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) -- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [An Introduction to Kong](https://www.baeldung.com/kong) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml index e1299a6a16..5efcffdf03 100644 --- a/spring-boot-modules/spring-boot/pom.xml +++ b/spring-boot-modules/spring-boot/pom.xml @@ -44,22 +44,6 @@ spring-boot-starter-actuator - - com.graphql-java - graphql-spring-boot-starter - ${graphql-spring-boot-starter.version} - - - com.graphql-java - graphql-java-tools - ${graphql-java-tools.version} - - - com.graphql-java - graphiql-spring-boot-starter - ${graphiql-spring-boot-starter.version} - - org.springframework.boot spring-boot-starter-tomcat @@ -104,18 +88,6 @@ provided - - org.togglz - togglz-spring-boot-starter - ${togglz.version} - - - - org.togglz - togglz-spring-security - ${togglz.version} - - org.apache.activemq artemis-server @@ -204,11 +176,7 @@ com.baeldung.intro.App 8.5.11 - 2.4.1.Final 1.9.0 - 5.0.2 - 5.0.2 - 5.2.4 18.0 @ diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java index eb091b4695..d2bb217c2f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -1,13 +1,9 @@ package com.baeldung.demo; -import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - @SpringBootApplication -@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties index 44649fc1c0..142e6c8e6f 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -21,12 +21,6 @@ spring.jmx.enabled=true ## for pretty printing of json when endpoints accessed over HTTP http.mappers.jsonPrettyPrint=true -## Configuring info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application G1 -info.app.version=1.0.0 -info.java-vendor = ${java.specification.vendor} - logging.level.org.springframework=INFO #Servlet Configuration diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages.properties b/spring-boot-modules/spring-boot/src/main/resources/messages.properties deleted file mode 100644 index e4dbc44c3f..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Hello! Welcome to our website! -lang.change=Change the language -lang.eng=English -lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties deleted file mode 100644 index ac5853717d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Bonjour! Bienvenue sur notre site! -lang.change=Changez la langue -lang.eng=Anglais -lang.fr=Francais \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/pom.xml index 5318ea6913..27037d6710 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-retry/pom.xml @@ -33,8 +33,20 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 0 + + + + + Hoxton.SR3 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java index 0f0a1c4255..decb77e7b9 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -24,6 +25,7 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java index 6fdad0f2a9..dc50fe76e6 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,6 +26,7 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties new file mode 100644 index 0000000000..640fb2c6a4 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties @@ -0,0 +1 @@ +logging.level.root=ERROR \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java index e4d7fcdc99..0ed06afd00 100644 --- a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java @@ -10,7 +10,7 @@ public class CustomSpringEventPublisher { @Autowired private ApplicationEventPublisher applicationEventPublisher; - public void publishEvent(final String message) { + public void publishCustomEvent(final String message) { System.out.println("Publishing custom event. "); final CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message); applicationEventPublisher.publishEvent(customSpringEvent); diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index 4f8035bcbe..d41f0114ca 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -17,7 +17,7 @@ public class AsynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() throws InterruptedException { - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing asynchronous custom event. "); } } diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index 1d624d2289..d4d718f980 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -22,7 +22,7 @@ public class SynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() { isTrue(!listener.isHitCustomEventHandler(), "The value should be false"); - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing synchronous custom event. "); isTrue(listener.isHitCustomEventHandler(), "Now the value should be changed to true"); } diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index 299de584ef..d7f875acd0 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -131,6 +131,12 @@ always + + + java.util.logging.config.file + src/test/resources/logging.properties + + diff --git a/spring-ejb/ejb-beans/src/test/resources/logging.properties b/spring-ejb/ejb-beans/src/test/resources/logging.properties new file mode 100644 index 0000000000..0a0ecef337 --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = SEVERE \ No newline at end of file diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index c07d6278cb..95418645fa 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -30,6 +30,7 @@ org.jooq jooq + ${org.jooq.version} @@ -201,7 +202,7 @@ - 3.11.7 + 3.12.4 1.0.0 1.5 1.0.0 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 3aeaa973af..674d9a2a14 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-katharsis/src/main/java/com/baeldung/Application.java b/spring-katharsis/src/main/java/com/baeldung/Application.java index 6c4f047b26..738afa039e 100644 --- a/spring-katharsis/src/main/java/com/baeldung/Application.java +++ b/spring-katharsis/src/main/java/com/baeldung/Application.java @@ -4,7 +4,7 @@ import io.katharsis.spring.boot.v3.KatharsisConfigV3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Import; @SpringBootApplication diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java index c5e6326075..a249def128 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -7,6 +7,9 @@ import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; import com.baeldung.persistence.model.Role; + +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +20,8 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public Role findOne(Long id, QuerySpec querySpec) { - return roleRepository.findOne(id); + Optional role = roleRepository.findById(id); + return role.isPresent()? role.get() : null; } @Override @@ -27,7 +31,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(roleRepository.findAll(ids)); + return querySpec.apply(roleRepository.findAllById(ids)); } @Override @@ -37,7 +41,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - roleRepository.delete(id); + roleRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java index 616431f3f0..af71da4727 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java @@ -6,6 +6,8 @@ import io.katharsis.queryspec.QuerySpec; import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +19,8 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public User findOne(Long id, QuerySpec querySpec) { - return userRepository.findOne(id); + Optional user = userRepository.findById(id); + return user.isPresent()? user.get() : null; } @Override @@ -27,7 +30,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(userRepository.findAll(ids)); + return querySpec.apply(userRepository.findAllById(ids)); } @Override @@ -37,7 +40,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - userRepository.delete(id); + userRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 066292c00f..d0b4a464c9 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -8,6 +8,7 @@ import io.katharsis.repository.RelationshipRepositoryV2; import io.katharsis.resource.list.ResourceList; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import com.baeldung.persistence.model.Role; @@ -31,7 +32,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void setRelations(User user, Iterable roleIds, String fieldName) { final Set roles = new HashSet(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -39,7 +40,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void addRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -47,7 +48,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void removeRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.removeAll(roleRepository.findAll(roleIds)); + roles.removeAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -60,7 +61,8 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { - final User user = userRepository.findOne(sourceId); + final Optional userOptional = userRepository.findById(sourceId); + User user = userOptional.isPresent() ? userOptional.get() : new User(); return querySpec.apply(user.getRoles()); } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index 120b3c62ee..415ec1723b 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis +server.servlet.context-path=/spring-katharsis katharsis.domainName=http://localhost:8082/spring-katharsis katharsis.pathPrefix=/ \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index fac6e1cb2e..67e3e3eab4 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -9,6 +9,7 @@ pom + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java new file mode 100644 index 0000000000..dfcfdc1117 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java @@ -0,0 +1,23 @@ +package com.baeldung.thymeleaf.blog; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.Random; + +@Controller +public class BlogController { + + @GetMapping("/blog/new") + public String newBlogPost(Model model) { + // Set a random ID so we can see it in the HTML form + BlogDTO blog = new BlogDTO(); + blog.setBlogId(Math.abs(new Random().nextLong() % 1000000)); + + model.addAttribute("blog", blog); + + return "blog/blog-new"; + } + +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java new file mode 100644 index 0000000000..44c77be5ce --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java @@ -0,0 +1,66 @@ +package com.baeldung.thymeleaf.blog; + +import java.util.Date; + +public class BlogDTO { + + private long blogId; + + private String title; + + private String body; + + private String author; + + private String category; + + private Date publishedDate; + + public long getBlogId() { + return blogId; + } + + public void setBlogId(long blogId) { + this.blogId = blogId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getPublishedDate() { + return publishedDate; + } + + public void setPublishedDate(Date publishedDate) { + this.publishedDate = publishedDate; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html new file mode 100644 index 0000000000..10747b4b07 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html @@ -0,0 +1,36 @@ + + + + + Hidden Input Examples + + + +

Hidden Input Example 1

+
+ + + + + +
+ +

Hidden Input Example 2

+
+ + + + + +
+ +

Hidden Input Example 3

+
+ + + + + +
+ + \ No newline at end of file diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index b467b3c503..f1d30cd7a1 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -31,7 +31,8 @@ rest-assured rest-testing selenium-junit-testng - spring-testing + spring-testing + spring-testing-2 test-containers testing-assertions testng diff --git a/testing-modules/spring-testing-2/.gitignore b/testing-modules/spring-testing-2/.gitignore new file mode 100644 index 0000000000..ffc5bf3bad --- /dev/null +++ b/testing-modules/spring-testing-2/.gitignore @@ -0,0 +1,3 @@ +.idea/** +target/** +*.iml \ No newline at end of file diff --git a/testing-modules/spring-testing-2/README.md b/testing-modules/spring-testing-2/README.md new file mode 100644 index 0000000000..729105e3fd --- /dev/null +++ b/testing-modules/spring-testing-2/README.md @@ -0,0 +1 @@ +## Relevant Articles: diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml new file mode 100644 index 0000000000..c7ca2804fb --- /dev/null +++ b/testing-modules/spring-testing-2/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + spring-testing-2 + 0.1-SNAPSHOT + spring-testing-2 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.postgresql + postgresql + runtime + + + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + + + + 2.1.9.RELEASE + 2.1.9.RELEASE + 1.12.2 + + \ No newline at end of file diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java new file mode 100644 index 0000000000..6b6bfb7bd6 --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java @@ -0,0 +1,45 @@ +package com.baeldung.dynamicproperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +import static javax.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "articles") +public class Article { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Long id; + + private String title; + + private String content; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java new file mode 100644 index 0000000000..3f3731f6dc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ArticleRepository extends JpaRepository { +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java new file mode 100644 index 0000000000..d64bd965fc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamicPropertiesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamicPropertiesApplication.class, args); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java new file mode 100644 index 0000000000..74c31229bd --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +public class ArticleLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + @Autowired + private ArticleRepository articleRepository; + + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", + () -> String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort())); + registry.add("spring.datasource.username", () -> "postgres"); + registry.add("spring.datasource.password", () -> "pass"); + } + + @Test + void givenAnArticle_whenPersisted_thenCanBeFoundInTheDb() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java new file mode 100644 index 0000000000..bb3ad28365 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@ActiveProfiles("pg") +@ExtendWith(PostgreSQLExtension.class) +public class ArticleTestFixtureLiveTest { + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java new file mode 100644 index 0000000000..87234505a9 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +@ContextConfiguration(initializers = ArticleTraditionalLiveTest.EnvInitializer.class) +class ArticleTraditionalLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + static class EnvInitializer implements ApplicationContextInitializer { + + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + TestPropertyValues.of( + String.format("spring.datasource.url=jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()), + "spring.datasource.username=postgres", + "spring.datasource.password=pass" + ).applyTo(applicationContext); + } + } + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java new file mode 100644 index 0000000000..8c08ad67d7 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.testcontainers.containers.PostgreSQLContainer; + +public class PostgreSQLExtension implements BeforeAllCallback, AfterAllCallback { + + private PostgreSQLContainer postgres; + + @Override + public void beforeAll(ExtensionContext context) { + postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + postgres.start(); + String jdbcUrl = String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()); + System.setProperty("spring.datasource.url", jdbcUrl); + System.setProperty("spring.datasource.username", "postgres"); + System.setProperty("spring.datasource.password", "pass"); + } + + @Override + public void afterAll(ExtensionContext context) { + postgres.stop(); + } +} diff --git a/testing-modules/spring-testing-2/src/test/resources/application-pg.properties b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties new file mode 100644 index 0000000000..cb7bff1889 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties @@ -0,0 +1,2 @@ +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 0a7c4b0860..fa0f666c7f 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,11 +18,45 @@ logback-classic 1.2.3 + + org.junit.jupiter + junit-jupiter-engine + 5.6.2 + test + + + org.junit.jupiter + junit-jupiter-api + 5.6.2 + test + org.assertj assertj-core - 3.15.0 + 3.16.1 + test + + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.apache.commons + commons-collections4 + 4.4 test
+ + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java new file mode 100644 index 0000000000..bf278cea90 --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.listassert; + +import org.apache.commons.collections4.CollectionUtils; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OrderAgnosticListComparisonUnitTest { + + private final List first = Arrays.asList(1, 3, 4, 6, 8); + private final List second = Arrays.asList(8, 1, 6, 3, 4); + private final List third = Arrays.asList(1, 3, 3, 6, 6); + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrue() { + assertTrue(first.size() == second.size() && first.containsAll(second) && second.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeFalse() { + assertFalse(first.size() == third.size() && first.containsAll(third) && third.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() { + MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() { + assertThat(first).hasSameElementsAs(second); + } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() { + List a = Arrays.asList("a", "a", "b", "c"); + List b = Arrays.asList("a", "b", "c"); + + assertThat(a).hasSameElementsAs(b); + } +}