From 6a2fcd54c33f583e28b6bd379948066a18171a05 Mon Sep 17 00:00:00 2001 From: Vishal Date: Wed, 12 Aug 2020 09:57:39 +0530 Subject: [PATCH 01/72] Add unit test to assert two list equality without considering order of elements in it. --- testing-modules/testing-assertions/pom.xml | 12 +++++ .../OrderAgnosticListComparison.java | 46 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 0a7c4b0860..fe8c86d058 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -24,5 +24,17 @@ 3.15.0 test + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.apache.commons + commons-collections4 + 4.4 + test + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java new file mode 100644 index 0000000000..b03723e5bd --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java @@ -0,0 +1,46 @@ +package com.baeldung.listassert; + +import org.hamcrest.Matchers; +import org.apache.commons.collections4.CollectionUtils; +import org.junit.Test; + + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class OrderAgnosticListComparison { + + 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); + + //In this test using simple JUnit assertion + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeTrue() { + assertTrue(first.size() == second.size() && + first.containsAll(second) && second.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeFalse() { + assertFalse(first.size() == third.size() && + first.containsAll(third) && third.containsAll(first)); + } + + //In this test using Hamcrest lib apis for assertion + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeEqual() { + assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + //In this test asserting lists using Apache Commons apis + @Test + public void whenTestingForOrderAgnosticEqualityShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } +} From 3cbfd383edd32b2848286c643fbc53b5f7609718 Mon Sep 17 00:00:00 2001 From: Vishal Date: Mon, 17 Aug 2020 18:06:20 +0530 Subject: [PATCH 02/72] Refactor | Add common formatting, remove comments, update test class name,follow test method naming convention and use Junit5 --- testing-modules/testing-assertions/pom.xml | 22 +++++++++ .../OrderAgnosticListComparison.java | 46 ------------------- .../OrderAgnosticListComparisonUnitTest.java | 40 ++++++++++++++++ 3 files changed, 62 insertions(+), 46 deletions(-) delete mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java create mode 100644 testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index fe8c86d058..5bb6f5faaa 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,6 +18,18 @@ 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 @@ -37,4 +49,14 @@ test + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java deleted file mode 100644 index b03723e5bd..0000000000 --- a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparison.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.listassert; - -import org.hamcrest.Matchers; -import org.apache.commons.collections4.CollectionUtils; -import org.junit.Test; - - -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class OrderAgnosticListComparison { - - 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); - - //In this test using simple JUnit assertion - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeTrue() { - assertTrue(first.size() == second.size() && - first.containsAll(second) && second.containsAll(first)); - } - - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeFalse() { - assertFalse(first.size() == third.size() && - first.containsAll(third) && third.containsAll(first)); - } - - //In this test using Hamcrest lib apis for assertion - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeEqual() { - assertThat(first, Matchers.containsInAnyOrder(second.toArray())); - } - - //In this test asserting lists using Apache Commons apis - @Test - public void whenTestingForOrderAgnosticEqualityShouldBeTrueIfEqualOtherwiseFalse() { - assertTrue(CollectionUtils.isEqualCollection(first, second)); - assertFalse(CollectionUtils.isEqualCollection(first, third)); - } -} 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..9ef6f203af --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.listassert; + +import org.apache.commons.collections4.CollectionUtils; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.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() { + assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } +} From f44cc311bd672013c4b230960004fcab7e20dd60 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Sat, 22 Aug 2020 12:30:44 +0200 Subject: [PATCH 03/72] Added aggregate operations --- .../kotlin/collections/AggregateOperations.kt | 131 ++++++++++++++++++ .../AggregateOperationsUnitTest.kt | 104 ++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt create mode 100644 core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt new file mode 100644 index 0000000000..854190382c --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt @@ -0,0 +1,131 @@ +package com.baeldung.kotlin.collections + +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 { + println("fold operation") + val result = numbers.fold(100) { total, it -> + println("total = $total, it = $it") + total - it + } + println(result) // ((((100 - 1)-15)-3)-8) = 73 + return result + } + + fun foldRightList(): Int { + println("foldRight operation") + val result = numbers.foldRight(100) { it, total -> + println("total = $total, it = $it") + total - it + } + println(result) // ((((100-8)-3)-15)-1) = 73 + return result + } + + fun foldIndexedList(): Int { + println("foldIndexed operation") + val result = numbers.foldIndexed(100) { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((100 - 3)-8) = 89 + return result + } + + fun foldRightIndexedList(): Int { + println("foldRightIndexed operation") + val result = numbers.foldRightIndexed(100) { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((100 - 8)-3) = 89 + return result + } + + fun reduceList(): Int { + println("reduce operation") + val result = numbers.reduce { total, it -> + println("total = $total, it = $it") + total - it + } + println(result) // (((1 - 15)-3)-8) = -25 + return result + } + + fun reduceRightList(): Int { + println("reduceRight operation") + val result = numbers.reduceRight() { it, total -> + println("total = $total, it = $it") + total - it + } + println(result) // ((8-3)-15)-1) = -11 + return result + } + + fun reduceIndexedList(): Int { + println("reduceIndexed operation") + val result = numbers.reduceIndexed { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((1-3)-8) = -10 + return result + } + + fun reduceRightIndexedList(): Int { + println("reduceRightIndexed operation") + val result = numbers.reduceRightIndexed { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } + println(result) // ((8-3) = 5 + return result + } +} diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt new file mode 100644 index 0000000000..1fb26760fc --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt @@ -0,0 +1,104 @@ +package com.baeldung.kotlin.collections + +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 From e7bef17346661b9d7e07a1b202e3730e066e71d1 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 22 Aug 2020 16:17:16 +0530 Subject: [PATCH 04/72] BAEL-4285 BAEL-4285 A Guide to ArrayStoreException --- .../array/ArrayStoreExceptionExample.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java new file mode 100644 index 0000000000..f82efec97b --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.array; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + System.out.println(array[0]); + } catch (ArrayStoreException e) { + e.printStackTrace(); + } + + } + +} From 456c3322e71657bd262120fa999ea415f7adb142 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 22 Aug 2020 16:20:07 +0530 Subject: [PATCH 05/72] Update README.md BAEL-4285 --- core-java-modules/core-java-arrays-guides/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 621443e4a9..85dfc37b3e 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) - [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) +- A Guide to ArrayStoreException From aa223e69eada94f4771d69cfecce0771a6742b52 Mon Sep 17 00:00:00 2001 From: Vishal Date: Sun, 23 Aug 2020 10:35:43 +0530 Subject: [PATCH 06/72] Add tests for AssertJ example and update assertj-core dependency version. --- testing-modules/testing-assertions/pom.xml | 2 +- .../OrderAgnosticListComparisonUnitTest.java | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 5bb6f5faaa..fa0f666c7f 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -33,7 +33,7 @@ org.assertj assertj-core - 3.15.0 + 3.16.1 test 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 index 9ef6f203af..bf278cea90 100644 --- 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 @@ -1,13 +1,14 @@ 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.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -29,7 +30,7 @@ public class OrderAgnosticListComparisonUnitTest { @Test public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() { - assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray())); } @Test @@ -37,4 +38,17 @@ public class OrderAgnosticListComparisonUnitTest { 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); + } } From 97252050f4f3235715c9b8dc4032a44854c99775 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sun, 23 Aug 2020 17:36:23 +0530 Subject: [PATCH 07/72] Added code for BAEL-4095 --- spring-boot-modules/pom.xml | 1 + .../spring-boot-swagger/pom.xml | 41 +++++++++++++ .../SpringBootSwaggerApplication.java | 13 ++++ .../configuration/SwaggerConfiguration.java | 61 +++++++++++++++++++ .../controller/RegularRestController.java | 35 +++++++++++ .../src/main/resources/application.properties | 0 6 files changed, 151 insertions(+) create mode 100644 spring-boot-modules/spring-boot-swagger/pom.xml create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java create mode 100644 spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties 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-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..73dfe85387 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -0,0 +1,61 @@ +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 From 14260c7d3002a6a36124eb4ee27429e5657f7ffa Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Mon, 24 Aug 2020 01:00:05 +0530 Subject: [PATCH 08/72] updated spring data, mongodb versions --- .../spring-data-mongodb/pom.xml | 26 +++++++++++-- .../java/com/baeldung/config/MongoConfig.java | 37 +++++++++++++------ .../baeldung/config/SimpleMongoConfig.java | 9 ++++- .../src/main/resources/mongoConfig.xml | 2 +- .../aggregation/ZipsAggregationLiveTest.java | 19 +++++++--- .../com/baeldung/gridfs/GridFSLiveTest.java | 2 +- .../mongotemplate/DocumentQueryLiveTest.java | 3 +- .../MongoTemplateQueryLiveTest.java | 2 +- .../repository/UserRepositoryLiveTest.java | 3 +- 9 files changed, 77 insertions(+), 26 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index fb80ba33ac..46dbc270c3 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -18,6 +18,19 @@ spring-data-mongodb ${org.springframework.data.version} + + + org.mongodb + mongodb-driver-core + ${mongodb-driver.version} + + + + org.mongodb + mongodb-driver-sync + ${mongodb-driver.version} + + org.springframework.data @@ -66,6 +79,12 @@ com.querydsl querydsl-mongodb ${querydsl.version} + + + org.mongodb + mongo-java-driver + + com.querydsl @@ -96,12 +115,13 @@ - 2.1.9.RELEASE - 4.1.4 + 3.0.3.RELEASE + 4.3.1 1.1.3 - 1.9.2 + 4.1.0 3.2.0.RELEASE Lovelace-SR9 + 4.1.0 diff --git a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 9fa90acf86..6851b5df6e 100644 --- a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,16 +1,18 @@ package com.baeldung.config; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; -import converter.ZonedDateTimeReadConverter; -import converter.ZonedDateTimeWriteConverter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; -import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.MongoTransactionManager; -import org.springframework.data.mongodb.config.AbstractMongoConfiguration; +import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @@ -18,14 +20,23 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie import com.baeldung.converter.UserWriterConverter; import com.baeldung.event.CascadeSaveMongoEventListener; import com.baeldung.event.UserCascadeSaveMongoEventListener; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; + +import converter.ZonedDateTimeReadConverter; +import converter.ZonedDateTimeWriteConverter; @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") -public class MongoConfig extends AbstractMongoConfiguration { +public class MongoConfig extends AbstractMongoClientConfiguration { private final List> converters = new ArrayList>(); + @Autowired + private MappingMongoConverter mongoConverter; + @Override protected String getDatabaseName() { return "test"; @@ -33,12 +44,16 @@ public class MongoConfig extends AbstractMongoConfiguration { @Override public MongoClient mongoClient() { - return new MongoClient("127.0.0.1", 27017); + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder() + .applyConnectionString(connectionString) + .build(); + return MongoClients.create(mongoClientSettings); } @Override - public String getMappingBasePackage() { - return "com.baeldung"; + public Collection getMappingBasePackages() { + return Collections.singleton("com.baeldung"); } @Bean @@ -61,11 +76,11 @@ public class MongoConfig extends AbstractMongoConfiguration { @Bean public GridFsTemplate gridFsTemplate() throws Exception { - return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); + return new GridFsTemplate(mongoDbFactory(), mongoConverter); } @Bean - MongoTransactionManager transactionManager(MongoDbFactory dbFactory) { + MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { return new MongoTransactionManager(dbFactory); } diff --git a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index c3ddad5a82..ac823c653f 100644 --- a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -5,7 +5,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") @@ -13,7 +16,9 @@ public class SimpleMongoConfig { @Bean public MongoClient mongo() throws Exception { - return new MongoClient("localhost"); + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); + return MongoClients.create(mongoClientSettings); } @Bean diff --git a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml index d59ebcef6e..074a203b1a 100644 --- a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml +++ b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml @@ -12,7 +12,7 @@ - + diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 1002dc79eb..dfc3205040 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -40,7 +40,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.aggregation.model.StatePopulation; import com.baeldung.config.MongoConfig; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -61,7 +64,7 @@ public class ZipsAggregationLiveTest { @BeforeClass public static void setupTests() throws Exception { - client = new MongoClient(); + client = mongoClient(); MongoDatabase testDB = client.getDatabase("test"); MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); @@ -75,19 +78,25 @@ public class ZipsAggregationLiveTest { @AfterClass public static void tearDown() throws Exception { - client = new MongoClient(); + client = mongoClient(); MongoDatabase testDB = client.getDatabase("test"); MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); client.close(); } + + private static MongoClient mongoClient() throws Exception { + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); + return MongoClients.create(mongoClientSettings); + } @Test public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() { GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop"); MatchOperation filterStates = match(new Criteria("statePop").gt(10000000)); - SortOperation sortByPopDesc = sort(new Sort(Direction.DESC, "statePop")); + SortOperation sortByPopDesc = sort(Sort.by(Direction.DESC, "statePop")); Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc); AggregationResults result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class); @@ -119,7 +128,7 @@ public class ZipsAggregationLiveTest { GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop"); GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop"); - SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop")); + SortOperation sortByAvgPopAsc = sort(Sort.by(Direction.ASC, "avgCityPop")); ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state") .andExpression("avgCityPop").as("statePop"); LimitOperation limitToOnlyFirstDoc = limit(1); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index d25b9ece4f..1504c2af68 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -113,7 +113,7 @@ public class GridFSLiveTest { assertNotNull(gridFSFile.getUploadDate()); // assertNull(gridFSFile.getAliases()); assertNotNull(gridFSFile.getChunkSize()); - assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png")); + //assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png")); assertThat(gridFSFile.getFilename(), is("test.png")); assertThat(gridFSFile.getMetadata().get("user"), is("alex")); } diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index e5e4a188ec..6172cc6b1d 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -186,7 +187,7 @@ public class DocumentQueryLiveTest { mongoTemplate.insert(user); Query query = new Query(); - query.with(new Sort(Sort.Direction.ASC, "age")); + query.with(Sort.by(Direction.ASC, "age")); List users = mongoTemplate.find(query, User.class); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index 4f62f0d7a7..3c4c5d2037 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -137,7 +137,7 @@ public class MongoTemplateQueryLiveTest { mongoTemplate.insert(user); Query query = new Query(); - query.with(new Sort(Sort.Direction.ASC, "age")); + query.with(Sort.by(Direction.ASC, "age")); List users = mongoTemplate.find(query, User.class); assertThat(users.size(), is(3)); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index dd7215af7e..a2fa567603 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -14,6 +14,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -127,7 +128,7 @@ public class UserRepositoryLiveTest { user.setName("Adam"); mongoOps.insert(user); - final List users = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + final List users = userRepository.findAll(Sort.by(Direction.ASC, "name")); assertThat(users.size(), is(2)); assertThat(users.get(0).getName(), is("Adam")); From cec243af0deadbdfd512dc4e4dbe9380f1ef066d Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:01:12 +0530 Subject: [PATCH 09/72] Update README.md --- core-java-modules/core-java-arrays-guides/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 85dfc37b3e..621443e4a9 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -6,4 +6,3 @@ This module contains complete guides about arrays in Java - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) - [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) -- A Guide to ArrayStoreException From da1d54699f2a42dd08594dea74b6eeb9faa9193c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:07:38 +0530 Subject: [PATCH 10/72] changing package changing package --- .../ArrayStoreExceptionExample.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java 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..ab485ca867 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + System.out.println(array[0]); + } catch (ArrayStoreException e) { + e.printStackTrace(); + } + + } + +} From 935b4c1278e5e6f0daef5d135f7f94176fdf7ded Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 11:09:01 +0530 Subject: [PATCH 11/72] Delete ArrayStoreExceptionExample.java --- .../array/ArrayStoreExceptionExample.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java deleted file mode 100644 index f82efec97b..0000000000 --- a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/ArrayStoreExceptionExample.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.array; - -public class ArrayStoreExceptionExample { - - public static void main(String[] args) { - - try { - Object array[] = new String[5]; - array[0] = 2; - System.out.println(array[0]); - } catch (ArrayStoreException e) { - e.printStackTrace(); - } - - } - -} From 765629be47187a94ee36b2ac1df487cb869677a4 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Mon, 24 Aug 2020 12:02:02 +0530 Subject: [PATCH 12/72] Adding File --- .../arraystoreexception/ArrayStoreExampleCE.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java 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; + } + +} From 82203b222e89543accda497ec9450db0adbb6e73 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Mon, 24 Aug 2020 09:59:39 +0200 Subject: [PATCH 13/72] Removed print statements --- .../kotlin/collections/AggregateOperations.kt | 56 ++++++------------- 1 file changed, 16 insertions(+), 40 deletions(-) diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt index 854190382c..3a348aafaa 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt @@ -50,82 +50,58 @@ class AggregateOperations { } fun foldList(): Int { - println("fold operation") - val result = numbers.fold(100) { total, it -> + return numbers.fold(100) { total, it -> println("total = $total, it = $it") total - it - } - println(result) // ((((100 - 1)-15)-3)-8) = 73 - return result + } // ((((100 - 1)-15)-3)-8) = 73 } fun foldRightList(): Int { - println("foldRight operation") - val result = numbers.foldRight(100) { it, total -> + return numbers.foldRight(100) { it, total -> println("total = $total, it = $it") total - it - } - println(result) // ((((100-8)-3)-15)-1) = 73 - return result + } // ((((100-8)-3)-15)-1) = 73 } fun foldIndexedList(): Int { - println("foldIndexed operation") - val result = numbers.foldIndexed(100) { index, total, it -> + return numbers.foldIndexed(100) { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((100 - 3)-8) = 89 - return result + } // ((100 - 3)-8) = 89 } fun foldRightIndexedList(): Int { - println("foldRightIndexed operation") - val result = numbers.foldRightIndexed(100) { index, it, total -> + return numbers.foldRightIndexed(100) { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((100 - 8)-3) = 89 - return result + } // ((100 - 8)-3) = 89 } fun reduceList(): Int { - println("reduce operation") - val result = numbers.reduce { total, it -> + return numbers.reduce { total, it -> println("total = $total, it = $it") total - it - } - println(result) // (((1 - 15)-3)-8) = -25 - return result + } // (((1 - 15)-3)-8) = -25 } fun reduceRightList(): Int { - println("reduceRight operation") - val result = numbers.reduceRight() { it, total -> + return numbers.reduceRight() { it, total -> println("total = $total, it = $it") total - it - } - println(result) // ((8-3)-15)-1) = -11 - return result + } // ((8-3)-15)-1) = -11 } fun reduceIndexedList(): Int { - println("reduceIndexed operation") - val result = numbers.reduceIndexed { index, total, it -> + return numbers.reduceIndexed { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((1-3)-8) = -10 - return result + } // ((1-3)-8) = -10 } fun reduceRightIndexedList(): Int { - println("reduceRightIndexed operation") - val result = numbers.reduceRightIndexed { index, it, total -> + return numbers.reduceRightIndexed { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total - } - println(result) // ((8-3) = 5 - return result + } // ((8-3) = 5 } } From c02caaac8924943a3621baf0f7f465c228b557b2 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Mon, 24 Aug 2020 09:56:00 -0600 Subject: [PATCH 14/72] BAEL-4224: Hidden inputs with thymeleaf --- .../thymeleaf/blog/BlogController.java | 24 +++++++ .../com/baeldung/thymeleaf/blog/BlogDTO.java | 66 +++++++++++++++++++ .../resources/templates/blog/blog-new.html | 36 ++++++++++ 3 files changed, 126 insertions(+) create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java create mode 100644 spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html 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..eee2d26409 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java @@ -0,0 +1,24 @@ +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 From 7d3e128323cb22c4fba4c88195d4037903bd4e26 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 26 Aug 2020 17:02:39 +0530 Subject: [PATCH 15/72] JAVA-33: Added comments in pom.xml with reason to not upgrade to boot-2 --- jhipster/pom.xml | 2 ++ spring-4/pom.xml | 1 + spring-activiti/pom.xml | 1 + spring-boot-modules/spring-boot-1/pom.xml | 1 + spring-remoting/remoting-hessian-burlap/pom.xml | 1 + 5 files changed, 6 insertions(+) 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/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/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-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 From 7b40f75cc9d0b157a9256793e5f60d2b30b9a98b Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 26 Aug 2020 17:04:08 +0530 Subject: [PATCH 16/72] JAVA-33: Moved spring-boot-camel to parent-boot-2 --- spring-boot-modules/spring-boot-camel/pom.xml | 10 +--- .../java/com/baeldung/camel/Application.java | 56 ++++++++++--------- .../src/main/resources/application.properties | 4 +- .../baeldung/SpringContextTest.java | 0 4 files changed, 35 insertions(+), 35 deletions(-) rename spring-boot-modules/spring-boot-camel/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) 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 From a2372358040d586e1a3cccf33fe151e6c5c566fb Mon Sep 17 00:00:00 2001 From: Rui Vilao Date: Wed, 26 Aug 2020 13:18:37 +0100 Subject: [PATCH 17/72] BAEL-4132: How to create a temporary directory/folder in Java? --- .../TemporaryDirectoriesUnitTest.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java new file mode 100644 index 0000000000..470e06ef96 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.tempdirectory; + +import org.apache.commons.io.FileUtils; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * Tests several possibilities on how to create + * temporary directories. + * + * @author Rui Vilao (rpvilao@gmail.com) + */ +public class TemporaryDirectoriesUnitTest { + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithPlainJava_thenInsideOSTempDirStructure() throws IOException { + final String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath(); + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithGuava_thenInsideOSTempDirStructure() throws IOException { + final String tmpdir = com.google.common.io.Files.createTempDir().getAbsolutePath(); + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithApacheCommonsIo_thenInsideOSTempDirStructure() throws IOException { + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + final Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString()); + final String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath(); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixWithTargetSpecified_whenCreatePlainJava_thenInsideTarget() throws IOException { + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix"); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + } + + @Test + public void givenTempDirWithPrefixWithTargetSpecifiedWithDeleteOnExit_whenCreatePlainJava_thenInsideTarget() throws IOException { + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix"); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + tmpdir.toFile().deleteOnExit(); + // we can really assert this test, just as an example. + } + + @Test + public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException { + final FileAttribute> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------")); + + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + assertThat(tmpdir.toFile().canWrite()).isFalse(); + } +} From 9c09e01c0327dcb0c75569a065482670ea162286 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 27 Aug 2020 22:16:56 +0200 Subject: [PATCH 18/72] JAVA-2431: Fix README.md files --- drools/README.MD | 1 + logging-modules/log-mdc/README.md | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) 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/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 From 544c3667538a284797dde4dda7f11f446949a5a2 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:54:52 +0530 Subject: [PATCH 19/72] JAVA-84: Moved 1 article to spring-boot-di --- spring-boot-modules/spring-boot-di/{README.MD => README.md} | 1 + spring-boot-modules/spring-boot-di/pom.xml | 6 ++++++ .../main/java/com/baeldung/displayallbeans/Application.java | 0 .../baeldung/displayallbeans/controller/FooController.java | 0 .../com/baeldung/displayallbeans/service/FooService.java | 0 .../displayallbeans/DisplayBeanIntegrationTest.java | 0 6 files changed, 7 insertions(+) rename spring-boot-modules/spring-boot-di/{README.MD => README.md} (81%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/Application.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/controller/FooController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/main/java/com/baeldung/displayallbeans/service/FooService.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-di}/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java (100%) 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 From 52721a78d6b5c52525c1e8c9af2e00b4b9cf0eab Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:56:09 +0530 Subject: [PATCH 20/72] JAVA-84: Moved 3 articles to spring-boot-libraries --- .../spring-boot-libraries/README.md | 3 + .../spring-boot-libraries/pom.xml | 31 +++- .../com/baeldung/demo/DemoApplication.java | 18 ++ .../java/com/baeldung/graphql/Author.java | 0 .../java/com/baeldung/graphql/AuthorDao.java | 0 .../com/baeldung/graphql/AuthorResolver.java | 0 .../graphql/GraphqlConfiguration.java | 0 .../java/com/baeldung/graphql/Mutation.java | 0 .../main/java/com/baeldung/graphql/Post.java | 0 .../java/com/baeldung/graphql/PostDao.java | 0 .../com/baeldung/graphql/PostResolver.java | 0 .../main/java/com/baeldung/graphql/Query.java | 0 .../com/baeldung/kong/QueryController.java | 0 .../main/java/com/baeldung/kong/StockApp.java | 0 .../java/com/baeldung/toggle/Employee.java | 37 ++++ .../baeldung/toggle/EmployeeRepository.java | 0 .../baeldung/toggle/FeatureAssociation.java | 0 .../com/baeldung/toggle/FeaturesAspect.java | 0 .../java/com/baeldung/toggle/MyFeatures.java | 0 .../com/baeldung/toggle/SalaryController.java | 0 .../com/baeldung/toggle/SalaryService.java | 0 .../baeldung/toggle/ToggleApplication.java | 0 .../baeldung/toggle/ToggleConfiguration.java | 0 .../baeldung/kong/KongAdminAPILiveTest.java | 170 ++++++++++++++++++ .../kong/KongLoadBalanceLiveTest.java | 75 ++++++++ .../com/baeldung/kong/domain/APIObject.java | 54 ++++++ .../baeldung/kong/domain/ConsumerObject.java | 35 ++++ .../baeldung/kong/domain/KeyAuthObject.java | 21 +++ .../baeldung/kong/domain/PluginObject.java | 30 ++++ .../baeldung/kong/domain/TargetObject.java | 31 ++++ .../baeldung/kong/domain/UpstreamObject.java | 21 +++ .../toggle/ToggleIntegrationTest.java | 62 +++++++ spring-boot-modules/spring-boot/pom.xml | 32 ---- 33 files changed, 587 insertions(+), 33 deletions(-) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Author.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/AuthorDao.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/AuthorResolver.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Mutation.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Post.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/PostDao.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/PostResolver.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/graphql/Query.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/kong/QueryController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/kong/StockApp.java (100%) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/EmployeeRepository.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/FeatureAssociation.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/FeaturesAspect.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/MyFeatures.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/SalaryController.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/SalaryService.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/ToggleApplication.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-libraries}/src/main/java/com/baeldung/toggle/ToggleConfiguration.java (100%) create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.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-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java new file mode 100644 index 0000000000..92d2286518 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java @@ -0,0 +1,170 @@ +package com.baeldung.kong; + +import com.baeldung.kong.domain.APIObject; +import com.baeldung.kong.domain.ConsumerObject; +import com.baeldung.kong.domain.KeyAuthObject; +import com.baeldung.kong.domain.PluginObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit4.SpringRunner; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +/** + * @author aiet + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class) +public class KongAdminAPILiveTest { + + private String getStockPrice(String code) { + try { + return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class); + } catch (Exception ignored) { + } + return null; + } + + @Before + public void init() { + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { + String response = getStockPrice("btc"); + assertEquals("10000", response); + + response = getStockPrice("eth"); + assertEquals("N/A", response); + } + + @Test + public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { + restTemplate.delete("http://localhost:8001/apis/stock-api"); + + APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/"); + HttpEntity apiEntity = new HttpEntity<>(stockAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + + assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode()); + + addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode()); + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + + assertTrue(apiListResp.contains("stock-api")); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + + assertEquals("10000", stockPriceResp.getBody()); + } + + @Test + public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() { + restTemplate.delete("http://localhost:8001/consumers/eugenp"); + + ConsumerObject consumer = new ConsumerObject("eugenp"); + HttpEntity addConsumerEntity = new HttpEntity<>(consumer); + ResponseEntity addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class); + + assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode()); + + addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class); + assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode()); + + String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); + assertTrue(consumerListResp.contains("eugenp")); + } + + @Test + public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception { + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + if (!apiListResp.contains("stock-api")) { + givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); + } + + PluginObject authPlugin = new PluginObject("key-auth"); + ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); + + assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); + + String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class); + assertTrue(pluginsResp.contains("key-auth")); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode()); + } + + @Test + public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception { + String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); + if (!apiListResp.contains("stock-api")) { + givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); + } + + String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); + if (!consumerListResp.contains("eugenp")) { + givenKongAdminAPI_whenAddAPIConsumer_thenAdded(); + } + + PluginObject authPlugin = new PluginObject("key-auth"); + ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); + assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); + + final String consumerKey = "eugenp.pass"; + KeyAuthObject keyAuth = new KeyAuthObject(consumerKey); + ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class); + + assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "stock.api"); + headers.set("apikey", consumerKey); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + + assertEquals("10000", stockPriceResp.getBody()); + + headers.set("apikey", "wrongpass"); + requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode()); + } + + @Test + public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception { + APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api"); + HttpEntity apiEntity = new HttpEntity<>(adminAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "admin.api"); + APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/"); + RequestEntity requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis")); + addAPIResp = restTemplate.exchange(requestEntity, String.class); + + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java new file mode 100644 index 0000000000..7cf67453a6 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java @@ -0,0 +1,75 @@ +package com.baeldung.kong; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +import java.net.URI; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.kong.domain.APIObject; +import com.baeldung.kong.domain.TargetObject; +import com.baeldung.kong.domain.UpstreamObject; + +/** + * @author aiet + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp") +public class KongLoadBalanceLiveTest { + + @Before + public void init() { + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } + + @Autowired + TestRestTemplate restTemplate; + + @Test + public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { + UpstreamObject upstream = new UpstreamObject("stock.api.service"); + ResponseEntity addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class); + assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode()); + + TargetObject testTarget = new TargetObject("localhost:8080", 10); + ResponseEntity addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class); + assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); + + TargetObject releaseTarget = new TargetObject("localhost:9090", 40); + addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class); + assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); + + APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/"); + HttpEntity apiEntity = new HttpEntity<>(stockAPI); + ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); + assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Host", "balanced.stock.api"); + for (int i = 0; i < 1000; i++) { + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); + ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); + assertEquals("10000", stockPriceResp.getBody()); + } + + int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class); + int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class); + + assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4); + } + +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..f386712444 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java @@ -0,0 +1,54 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class APIObject { + + public APIObject() { + } + + public APIObject(String name, String hosts, String upstream_url, String uris) { + this.name = name; + this.hosts = hosts; + this.upstream_url = upstream_url; + this.uris = uris; + } + + private String name; + private String hosts; + private String upstream_url; + private String uris; + + public String getUris() { + return uris; + } + + public void setUris(String uris) { + this.uris = uris; + } + + public String getUpstream_url() { + return upstream_url; + } + + public void setUpstream_url(String upstream_url) { + this.upstream_url = upstream_url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..74bef8f2d1 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java @@ -0,0 +1,35 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class ConsumerObject { + + private String username; + private String custom_id; + + public ConsumerObject(String username) { + this.username = username; + } + + public ConsumerObject(String username, String custom_id) { + this.username = username; + this.custom_id = custom_id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getCustom_id() { + return custom_id; + } + + public void setCustom_id(String custom_id) { + this.custom_id = custom_id; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..80de6bfcd9 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java @@ -0,0 +1,21 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class KeyAuthObject { + + public KeyAuthObject(String key) { + this.key = key; + } + + private String key; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..c161fc9b54 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java @@ -0,0 +1,30 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class PluginObject { + + private String name; + private String consumer_id; + + public PluginObject(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getConsumer_id() { + return consumer_id; + } + + public void setConsumer_id(String consumer_id) { + this.consumer_id = consumer_id; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..79653e2846 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java @@ -0,0 +1,31 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class TargetObject { + + public TargetObject(String target, int weight) { + this.target = target; + this.weight = weight; + } + + private String target; + private int weight; + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/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 new file mode 100644 index 0000000000..6461381ac5 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java @@ -0,0 +1,21 @@ +package com.baeldung.kong.domain; + +/** + * @author aiet + */ +public class UpstreamObject { + + public UpstreamObject(String name) { + this.name = name; + } + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java new file mode 100644 index 0000000000..3213a10df9 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.toggle; + +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class) +@AutoConfigureMockMvc +public class ToggleIntegrationTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + + System.setProperty("employee.feature", "false"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + + emp = employeeRepository.findById(1L).orElse(null); + assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); + } + + @Test + public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception { + Employee emp = new Employee(1, 2000); + employeeRepository.save(emp); + + System.setProperty("employee.feature", "true"); + + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + + emp = employeeRepository.findById(1L).orElse(null); + assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); + } +} 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 @ From 5749d7ad23468ed7f2e071372be556f4b3925df0 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 28 Aug 2020 17:57:38 +0530 Subject: [PATCH 21/72] JAVA-84: Moved 1 article to spring-boot-testing --- .../spring-boot-testing/README.md | 1 + .../spring-boot-testing/pom.xml | 8 + .../com/baeldung/boot/testing}/Employee.java | 2 +- .../boot/testing}/EmployeeRepository.java | 2 +- .../boot/testing}/EmployeeRestController.java | 2 +- .../boot/testing}/EmployeeService.java | 2 +- .../boot/testing}/EmployeeServiceImpl.java | 2 +- .../src/main/resources/application.properties | 4 +- .../persistence-generic-entity.properties | 8 + .../EmployeeControllerIntegrationTest.java | 39 ++-- .../EmployeeRepositoryIntegrationTest.java | 7 +- ...EmployeeRestControllerIntegrationTest.java | 12 +- .../EmployeeServiceImplIntegrationTest.java | 11 +- .../com/baeldung/boot/testing}/JsonUtil.java | 2 +- .../application-integrationtest.properties | 0 .../src/test/resources/application.properties | 4 +- .../spring-boot/{README.MD => README.md} | 5 - .../com/baeldung/demo/DemoApplication.java | 4 - .../baeldung/kong/KongAdminAPILiveTest.java | 170 ------------------ .../kong/KongLoadBalanceLiveTest.java | 75 -------- .../com/baeldung/kong/domain/APIObject.java | 54 ------ .../baeldung/kong/domain/ConsumerObject.java | 35 ---- .../baeldung/kong/domain/KeyAuthObject.java | 21 --- .../baeldung/kong/domain/PluginObject.java | 30 ---- .../baeldung/kong/domain/TargetObject.java | 31 ---- .../baeldung/kong/domain/UpstreamObject.java | 21 --- .../toggle/ToggleIntegrationTest.java | 62 ------- 27 files changed, 70 insertions(+), 544 deletions(-) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/Employee.java (95%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeRepository.java (91%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeRestController.java (96%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeService.java (89%) rename spring-boot-modules/{spring-boot/src/main/java/com/baeldung/demo/boottest => spring-boot-testing/src/main/java/com/baeldung/boot/testing}/EmployeeServiceImpl.java (96%) create mode 100644 spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeControllerIntegrationTest.java (87%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeRepositoryIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeRestControllerIntegrationTest.java (87%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/EmployeeServiceImplIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot/src/test/java/com/baeldung/demo/boottest => spring-boot-testing/src/test/java/com/baeldung/boot/testing}/JsonUtil.java (91%) rename spring-boot-modules/{spring-boot => spring-boot-testing}/src/test/resources/application-integrationtest.properties (100%) rename spring-boot-modules/spring-boot/{README.MD => README.md} (79%) delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java delete mode 100644 spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java 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 79% rename from spring-boot-modules/spring-boot/README.MD rename to spring-boot-modules/spring-boot/README.md index c95fe51842..510864e339 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.md @@ -14,12 +14,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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/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/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java deleted file mode 100644 index 92d2286518..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.baeldung.kong; - -import com.baeldung.kong.domain.APIObject; -import com.baeldung.kong.domain.ConsumerObject; -import com.baeldung.kong.domain.KeyAuthObject; -import com.baeldung.kong.domain.PluginObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; -import org.springframework.test.context.junit4.SpringRunner; - -import java.net.URI; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; - -/** - * @author aiet - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class) -public class KongAdminAPILiveTest { - - private String getStockPrice(String code) { - try { - return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class); - } catch (Exception ignored) { - } - return null; - } - - @Before - public void init() { - System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); - } - - @Autowired - TestRestTemplate restTemplate; - - @Test - public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() { - String response = getStockPrice("btc"); - assertEquals("10000", response); - - response = getStockPrice("eth"); - assertEquals("N/A", response); - } - - @Test - public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { - restTemplate.delete("http://localhost:8001/apis/stock-api"); - - APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/"); - HttpEntity apiEntity = new HttpEntity<>(stockAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - - assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode()); - - addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode()); - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - - assertTrue(apiListResp.contains("stock-api")); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - - assertEquals("10000", stockPriceResp.getBody()); - } - - @Test - public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() { - restTemplate.delete("http://localhost:8001/consumers/eugenp"); - - ConsumerObject consumer = new ConsumerObject("eugenp"); - HttpEntity addConsumerEntity = new HttpEntity<>(consumer); - ResponseEntity addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class); - - assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode()); - - addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class); - assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode()); - - String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); - assertTrue(consumerListResp.contains("eugenp")); - } - - @Test - public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception { - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - if (!apiListResp.contains("stock-api")) { - givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); - } - - PluginObject authPlugin = new PluginObject("key-auth"); - ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); - - assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); - - String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class); - assertTrue(pluginsResp.contains("key-auth")); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode()); - } - - @Test - public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception { - String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class); - if (!apiListResp.contains("stock-api")) { - givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong(); - } - - String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class); - if (!consumerListResp.contains("eugenp")) { - givenKongAdminAPI_whenAddAPIConsumer_thenAdded(); - } - - PluginObject authPlugin = new PluginObject("key-auth"); - ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); - assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); - - final String consumerKey = "eugenp.pass"; - KeyAuthObject keyAuth = new KeyAuthObject(consumerKey); - ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class); - - assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "stock.api"); - headers.set("apikey", consumerKey); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - - assertEquals("10000", stockPriceResp.getBody()); - - headers.set("apikey", "wrongpass"); - requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode()); - } - - @Test - public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception { - APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api"); - HttpEntity apiEntity = new HttpEntity<>(adminAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "admin.api"); - APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/"); - RequestEntity requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis")); - addAPIResp = restTemplate.exchange(requestEntity, String.class); - - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java deleted file mode 100644 index 7cf67453a6..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.kong; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; - -import java.net.URI; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.kong.domain.APIObject; -import com.baeldung.kong.domain.TargetObject; -import com.baeldung.kong.domain.UpstreamObject; - -/** - * @author aiet - */ -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp") -public class KongLoadBalanceLiveTest { - - @Before - public void init() { - System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); - } - - @Autowired - TestRestTemplate restTemplate; - - @Test - public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { - UpstreamObject upstream = new UpstreamObject("stock.api.service"); - ResponseEntity addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class); - assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode()); - - TargetObject testTarget = new TargetObject("localhost:8080", 10); - ResponseEntity addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class); - assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); - - TargetObject releaseTarget = new TargetObject("localhost:9090", 40); - addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class); - assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode()); - - APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/"); - HttpEntity apiEntity = new HttpEntity<>(stockAPI); - ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); - assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Host", "balanced.stock.api"); - for (int i = 0; i < 1000; i++) { - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); - ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); - assertEquals("10000", stockPriceResp.getBody()); - } - - int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class); - int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class); - - assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4); - } - -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java deleted file mode 100644 index f386712444..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class APIObject { - - public APIObject() { - } - - public APIObject(String name, String hosts, String upstream_url, String uris) { - this.name = name; - this.hosts = hosts; - this.upstream_url = upstream_url; - this.uris = uris; - } - - private String name; - private String hosts; - private String upstream_url; - private String uris; - - public String getUris() { - return uris; - } - - public void setUris(String uris) { - this.uris = uris; - } - - public String getUpstream_url() { - return upstream_url; - } - - public void setUpstream_url(String upstream_url) { - this.upstream_url = upstream_url; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getHosts() { - return hosts; - } - - public void setHosts(String hosts) { - this.hosts = hosts; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java deleted file mode 100644 index 74bef8f2d1..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class ConsumerObject { - - private String username; - private String custom_id; - - public ConsumerObject(String username) { - this.username = username; - } - - public ConsumerObject(String username, String custom_id) { - this.username = username; - this.custom_id = custom_id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getCustom_id() { - return custom_id; - } - - public void setCustom_id(String custom_id) { - this.custom_id = custom_id; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java deleted file mode 100644 index 80de6bfcd9..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class KeyAuthObject { - - public KeyAuthObject(String key) { - this.key = key; - } - - private String key; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java deleted file mode 100644 index c161fc9b54..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class PluginObject { - - private String name; - private String consumer_id; - - public PluginObject(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getConsumer_id() { - return consumer_id; - } - - public void setConsumer_id(String consumer_id) { - this.consumer_id = consumer_id; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java deleted file mode 100644 index 79653e2846..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class TargetObject { - - public TargetObject(String target, int weight) { - this.target = target; - this.weight = weight; - } - - private String target; - private int weight; - - public String getTarget() { - return target; - } - - public void setTarget(String target) { - this.target = target; - } - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java deleted file mode 100644 index 6461381ac5..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kong.domain; - -/** - * @author aiet - */ -public class UpstreamObject { - - public UpstreamObject(String name) { - this.name = name; - } - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java deleted file mode 100644 index 3213a10df9..0000000000 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.toggle; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class) -@AutoConfigureMockMvc -public class ToggleIntegrationTest { - - @Autowired - private EmployeeRepository employeeRepository; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext wac; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception { - Employee emp = new Employee(1, 2000); - employeeRepository.save(emp); - - System.setProperty("employee.feature", "false"); - - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - - emp = employeeRepository.findById(1L).orElse(null); - assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); - } - - @Test - public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception { - Employee emp = new Employee(1, 2000); - employeeRepository.save(emp); - - System.setProperty("employee.feature", "true"); - - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); - - emp = employeeRepository.findById(1L).orElse(null); - assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); - } -} From e878b28d98896b0b0d35a1b63a104746eb73cb35 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sat, 29 Aug 2020 13:05:31 +0530 Subject: [PATCH 22/72] Splitted apiInfo to multiple lines. --- .../swagger2boot/configuration/SwaggerConfiguration.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 index 73dfe85387..7bacdde4c8 100644 --- 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 @@ -22,7 +22,9 @@ import springfox.documentation.swagger.web.UiConfigurationBuilder; 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()); + 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 From 597e537bd46a8324184c9c1d203a9c5eef9bbe6e Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 29 Aug 2020 23:04:29 +0200 Subject: [PATCH 23/72] Java-1458 Reduce logging - jhipster5 --- jhipster-5/bookstore-monolith/pom.xml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) 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 From dee331897721ee8fb4921128f39e9afaf235dc24 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 00:05:49 +0200 Subject: [PATCH 24/72] Java-1456 Reduce logging modules apache-spark, spring-boot-crud maven-assembly-plugin --- apache-spark/pom.xml | 1 + 1 file changed, 1 insertion(+) 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 From 71b9fd959aeb0b66e513c8965993db69d70ba58c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sun, 30 Aug 2020 14:19:34 +0530 Subject: [PATCH 25/72] Update ArrayStoreExceptionExample.java --- .../array/arraystoreexception/ArrayStoreExceptionExample.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 index ab485ca867..ce63fd6605 100644 --- 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 @@ -7,9 +7,8 @@ public class ArrayStoreExceptionExample { try { Object array[] = new String[5]; array[0] = 2; - System.out.println(array[0]); } catch (ArrayStoreException e) { - e.printStackTrace(); + // handle the exception } } From 3e89177d9b8d30c44623221050e5770af31b4f2a Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Sun, 30 Aug 2020 15:46:52 +0430 Subject: [PATCH 26/72] Fix the integrations tests in ribbon-client-service --- .../src/main/resources/application.yml | 1 - .../RibbonRetryFailureIntegrationTest.java | 7 +++++-- .../RibbonRetrySuccessIntegrationTest.java | 7 +++++-- .../spring/cloud/ribbon/retry/TestUtils.java | 18 ++++++++++++++++++ 4 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml index 29d2360793..a6f67772f2 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml @@ -9,7 +9,6 @@ weather-service: ribbon: eureka: enabled: false - listOfServers: http://localhost:8021, http://localhost:8022 ServerListRefreshInterval: 5000 MaxAutoRetries: 3 MaxAutoRetriesNextServer: 1 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..6a4fe4bd00 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 @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; +import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) @@ -24,8 +25,10 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(8021); - weatherServiceInstance2 = startApp(8022); + weatherServiceInstance1 = startApp(0); + weatherServiceInstance2 = startApp(0); + + setUpServices(weatherServiceInstance1, weatherServiceInstance2); } @AfterAll 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..281f69d0bc 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 @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; +import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -25,8 +26,10 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(8021); - weatherServiceInstance2 = startApp(8022); + weatherServiceInstance1 = startApp(0); + weatherServiceInstance2 = startApp(0); + + setUpServices(weatherServiceInstance1, weatherServiceInstance2); } private static ConfigurableApplicationContext startApp(int port) { diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java new file mode 100644 index 0000000000..67c7847cda --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.ribbon.retry; + +import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +class TestUtils { + + static int getWebAppPort(ConfigurableApplicationContext ctx) { + return ((AnnotationConfigServletWebServerApplicationContext) ctx).getWebServer().getPort(); + } + + static void setUpServices(ConfigurableApplicationContext service1, ConfigurableApplicationContext service2) { + int port1 = getWebAppPort(service1); + int port2 = getWebAppPort(service2); + String serversList = String.format("http://localhost:%d, http://localhost:%d", port1, port2); + System.setProperty("weather-service.ribbon.listOfServers", serversList); + } +} From fb36c068cd20d9b5d532e5d894d80ea0243d2823 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 30 Aug 2020 16:51:48 +0530 Subject: [PATCH 27/72] JAVA-33: Moved spring-katharsis to boot-2 --- spring-katharsis/pom.xml | 4 ++-- .../src/main/java/com/baeldung/Application.java | 2 +- .../persistence/katharsis/RoleResourceRepository.java | 10 +++++++--- .../persistence/katharsis/UserResourceRepository.java | 9 ++++++--- .../katharsis/UserToRoleRelationshipRepository.java | 10 ++++++---- .../src/main/resources/application.properties | 2 +- 6 files changed, 23 insertions(+), 14 deletions(-) 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 From 531751568cacd590d923b17d1b41940872c46da9 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Sun, 30 Aug 2020 13:23:51 +0200 Subject: [PATCH 28/72] Moved to new module --- .../core-kotlin-collections-2/README.md | 7 +++ .../core-kotlin-collections-2/pom.xml | 47 +++++++++++++++++++ .../AggregateOperations.kt | 2 +- .../AggregateOperationsUnitTest.kt | 2 +- core-kotlin-modules/pom.xml | 1 + 5 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 core-kotlin-modules/core-kotlin-collections-2/README.md create mode 100644 core-kotlin-modules/core-kotlin-collections-2/pom.xml rename core-kotlin-modules/{core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections => core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate}/AggregateOperations.kt (98%) rename core-kotlin-modules/{core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections => core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate}/AggregateOperationsUnitTest.kt (98%) 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/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt similarity index 98% rename from core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt index 3a348aafaa..a09e101b59 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/AggregateOperations.kt +++ b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.collections +package com.baeldung.aggregate class AggregateOperations { private val numbers = listOf(1, 15, 3, 8) diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt similarity index 98% rename from core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt index 1fb26760fc..a619759b0a 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/AggregateOperationsUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt @@ -1,4 +1,4 @@ -package com.baeldung.kotlin.collections +package com.baeldung.aggregate import org.junit.jupiter.api.Test import kotlin.test.assertEquals 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 From d7e25cb6e99fbdb15566eb601e9a987ddcad5b29 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 14:35:18 +0200 Subject: [PATCH 29/72] Java-1462 Reduce logging - Modules core-java-io-2, spring-ejb-beans, spring-boot-security --- .../core-java-io-2/src/main/resources/logback.xml | 12 ++++++++++++ .../src/main/resources/logback.xml | 2 +- .../src/test/resources/application.properties | 2 ++ spring-ejb/ejb-beans/pom.xml | 6 ++++++ .../ejb-beans/src/test/resources/logging.properties | 2 ++ 5 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-io-2/src/main/resources/logback.xml create mode 100644 spring-boot-modules/spring-boot-security/src/test/resources/application.properties create mode 100644 spring-ejb/ejb-beans/src/test/resources/logging.properties 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/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-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 From 87f19ad21a6773abb6e9433122db951da3fc4771 Mon Sep 17 00:00:00 2001 From: mikr Date: Sun, 30 Aug 2020 16:54:15 +0200 Subject: [PATCH 30/72] Reduce logging - Modules api-gateway, spring-boot-springdoc, spring-zuul-rate-limiting, hibernate-ogm, jpa-hibernate-cascade-type --- .../hibernate-ogm/src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/hibernate.properties | 2 +- .../src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/logback.xml | 12 ++++++++++++ .../api-gateway/src/test/resources/logback.xml | 12 ++++++++++++ .../src/test/resources/application.properties | 1 + .../src/test/resources/logback.xml | 12 ++++++++++++ 7 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/hibernate-ogm/src/test/resources/logback.xml create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml create mode 100644 spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties create mode 100644 spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml 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/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/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-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 + + + + + + + From 5bcf243fdbba47e231c91dfe26b6330839c2de6f Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 31 Aug 2020 01:09:36 +0430 Subject: [PATCH 31/72] Revert "Fix the integrations tests in ribbon-client-service" This reverts commit 3e89177d --- .../src/main/resources/application.yml | 1 + .../RibbonRetryFailureIntegrationTest.java | 7 ++----- .../RibbonRetrySuccessIntegrationTest.java | 7 ++----- .../spring/cloud/ribbon/retry/TestUtils.java | 18 ------------------ 4 files changed, 5 insertions(+), 28 deletions(-) delete mode 100644 spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml index a6f67772f2..29d2360793 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/main/resources/application.yml @@ -9,6 +9,7 @@ weather-service: ribbon: eureka: enabled: false + listOfServers: http://localhost:8021, http://localhost:8022 ServerListRefreshInterval: 5000 MaxAutoRetries: 3 MaxAutoRetriesNextServer: 1 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 6a4fe4bd00..0f0a1c4255 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 @@ -10,7 +10,6 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; -import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RibbonClientApp.class) @@ -25,10 +24,8 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(0); - weatherServiceInstance2 = startApp(0); - - setUpServices(weatherServiceInstance1, weatherServiceInstance2); + weatherServiceInstance1 = startApp(8021); + weatherServiceInstance2 = startApp(8022); } @AfterAll 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 281f69d0bc..6fdad0f2a9 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 @@ -10,7 +10,6 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.ResponseEntity; -import static com.baeldung.spring.cloud.ribbon.retry.TestUtils.setUpServices; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -26,10 +25,8 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { - weatherServiceInstance1 = startApp(0); - weatherServiceInstance2 = startApp(0); - - setUpServices(weatherServiceInstance1, weatherServiceInstance2); + weatherServiceInstance1 = startApp(8021); + weatherServiceInstance2 = startApp(8022); } private static ConfigurableApplicationContext startApp(int port) { diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java deleted file mode 100644 index 67c7847cda..0000000000 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/TestUtils.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.spring.cloud.ribbon.retry; - -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -class TestUtils { - - static int getWebAppPort(ConfigurableApplicationContext ctx) { - return ((AnnotationConfigServletWebServerApplicationContext) ctx).getWebServer().getPort(); - } - - static void setUpServices(ConfigurableApplicationContext service1, ConfigurableApplicationContext service2) { - int port1 = getWebAppPort(service1); - int port2 = getWebAppPort(service2); - String serversList = String.format("http://localhost:%d, http://localhost:%d", port1, port2); - System.setProperty("weather-service.ribbon.listOfServers", serversList); - } -} From 5d7035cb19d39878422bda82e1c3b6b545024ec1 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 31 Aug 2020 01:25:37 +0430 Subject: [PATCH 32/72] Running two tests sequentially. --- spring-cloud/spring-cloud-ribbon-retry/pom.xml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) 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 From e0ebf5904faccb404a7e3bc6d8b4eb614b3dc880 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Mon, 31 Aug 2020 20:41:47 +0530 Subject: [PATCH 33/72] JAVA-84: Move articles out of spring-boot part 1 (#9950) * JAVA-84: Moved 1 article to spring-boot-actuator * JAVA-84: Moved 2 articles to spring-boot-mvc * JAVA-84: README changes for spring-boot module * JAVA-84: Moved classes to com.baeldung pkg to correct compilation issue --- .../{README.MD => README.md} | 1 + .../spring-boot-actuator/pom.xml | 8 ++ .../baeldung/endpoints/info/Application.java | 13 ++++ .../info/TotalUsersInfoContributor.java | 1 - .../com/baeldung/endpoints/info/User.java | 49 ++++++++++++ .../endpoints/info/UserRepository.java | 78 +++++++++++++++++++ .../src/main/resources/application.properties | 8 +- spring-boot-modules/spring-boot-mvc/README.md | 2 + .../SpringBootAnnotatedApp.java | 0 .../SpringBootPlainApp.java | 0 .../components/AttrListener.java | 0 .../components/EchoServlet.java | 0 .../components/HelloFilter.java | 0 .../components/HelloServlet.java | 0 .../InternationalizationApp.java | 0 .../config/MvcConfig.java | 0 .../config/PageController.java | 2 +- .../src/main/resources/messages.properties | 6 +- .../src/main/resources/messages_fr.properties | 6 +- .../resources/static/internationalization.js | 0 .../templates/thymeleaf}/international.html | 0 .../baeldung/SpringContextLiveTest.java | 0 .../baeldung/SpringContextTest.java | 0 ...otWithServletComponentIntegrationTest.java | 26 +++---- ...ithoutServletComponentIntegrationTest.java | 0 spring-boot-modules/spring-boot/README.md | 3 - .../src/main/resources/application.properties | 6 -- .../src/main/resources/messages.properties | 4 - .../src/main/resources/messages_fr.properties | 4 - 29 files changed, 181 insertions(+), 36 deletions(-) rename spring-boot-modules/spring-boot-actuator/{README.MD => README.md} (72%) create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java rename spring-boot-modules/{spring-boot => spring-boot-actuator}/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java (94%) create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java create mode 100644 spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/InternationalizationApp.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/config/MvcConfig.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/java/com/baeldung/internationalization/config/PageController.java (87%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/main/resources/static/internationalization.js (100%) rename spring-boot-modules/{spring-boot/src/main/resources/templates => spring-boot-mvc/src/main/resources/templates/thymeleaf}/international.html (100%) rename spring-boot-modules/spring-boot-mvc/src/test/java/{org => com}/baeldung/SpringContextLiveTest.java (100%) rename spring-boot-modules/spring-boot-mvc/src/test/java/{org => com}/baeldung/SpringContextTest.java (100%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java (94%) rename spring-boot-modules/{spring-boot => spring-boot-mvc}/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java (100%) delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/messages.properties delete mode 100644 spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties 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-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/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/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/README.md b/spring-boot-modules/spring-boot/README.md index 510864e339..5a45502fd8 100644 --- a/spring-boot-modules/spring-boot/README.md +++ b/spring-boot-modules/spring-boot/README.md @@ -8,12 +8,9 @@ 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) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - [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) 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 From 25b174930886c60d9b7e9b6a0003b1be4d906aed Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Mon, 31 Aug 2020 20:13:13 +0430 Subject: [PATCH 34/72] BAEL-4530: A Guide to @DynamicPropertySource in Spring (#9877) * A Guide to @DynamicPropertySource in Spring * Moving to a new module * Reverting the Changes in the original module --- testing-modules/pom.xml | 3 +- testing-modules/spring-testing-2/.gitignore | 3 + testing-modules/spring-testing-2/README.md | 1 + testing-modules/spring-testing-2/pom.xml | 57 +++++++++++++++++++ .../baeldung/dynamicproperties/Article.java | 45 +++++++++++++++ .../dynamicproperties/ArticleRepository.java | 6 ++ .../DynamicPropertiesApplication.java | 12 ++++ .../dynamicproperties/ArticleLiveTest.java | 50 ++++++++++++++++ .../ArticleTestFixtureLiveTest.java | 31 ++++++++++ .../ArticleTraditionalLiveTest.java | 57 +++++++++++++++++++ .../PostgreSQLExtension.java | 31 ++++++++++ .../test/resources/application-pg.properties | 2 + 12 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 testing-modules/spring-testing-2/.gitignore create mode 100644 testing-modules/spring-testing-2/README.md create mode 100644 testing-modules/spring-testing-2/pom.xml create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java create mode 100644 testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java create mode 100644 testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java create mode 100644 testing-modules/spring-testing-2/src/test/resources/application-pg.properties 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 From d4d7059add4837bc0b88e750a52cb09d1d447429 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Mon, 31 Aug 2020 10:34:01 -0600 Subject: [PATCH 35/72] Update BlogController.java Update formatting --- .../main/java/com/baeldung/thymeleaf/blog/BlogController.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 index eee2d26409..dfcfdc1117 100644 --- 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 @@ -10,8 +10,7 @@ import java.util.Random; public class BlogController { @GetMapping("/blog/new") - public String newBlogPost(Model model) - { + 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)); From d237c52a1f677b0cac7f59ca71bd0fa7a9ff6c95 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Mon, 31 Aug 2020 19:41:46 +0200 Subject: [PATCH 36/72] Java-75 update intro to reactor core (#9953) * Java-75 Update intro to Reactor Core * Java-75 Create package for introduction * Java-75 Update reactor version and align unit test with article Co-authored-by: mikr --- reactor-core/pom.xml | 2 +- .../{ => introduction}/ReactorIntegrationTest.java | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) rename reactor-core/src/test/java/com/baeldung/reactor/{ => introduction}/ReactorIntegrationTest.java (91%) 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 From c6d95556171005b68cc4a6194de97de2cb5406ff Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Mon, 31 Aug 2020 20:38:06 +0200 Subject: [PATCH 37/72] Refactored package --- .../baeldung/aggregate}/AggregateOperations.kt | 0 .../baeldung/aggregate}/AggregateOperationsUnitTest.kt | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/{com.baeldung.aggregate => com/baeldung/aggregate}/AggregateOperations.kt (100%) rename core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/{com.baeldung.aggregate => com/baeldung/aggregate}/AggregateOperationsUnitTest.kt (100%) 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 similarity index 100% rename from core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com.baeldung.aggregate/AggregateOperations.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt 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 similarity index 100% rename from core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com.baeldung.aggregate/AggregateOperationsUnitTest.kt rename to core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt From 026e3c511ef0181dffb883bbe95345f80fca353a Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Tue, 1 Sep 2020 04:27:53 +0430 Subject: [PATCH 38/72] Disabling Tomcat URL Stream Factory --- .../cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java | 2 ++ .../cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java | 2 ++ 2 files changed, 4 insertions(+) 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); } From 03ac0c0b5d331b1c67fa2af5c0b9e4614d7d5e7f Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:13:34 +0530 Subject: [PATCH 39/72] Added two space indent for the line continuation. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) 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 index 7bacdde4c8..4f85d90f5f 100644 --- 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 @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @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(); + .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(); } } From 994e25312b5d770f4aabdf14ac893fdd98b36467 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:28:46 +0530 Subject: [PATCH 40/72] Revert "Added two space indent for the line continuation." This reverts commit 03ac0c0b5d331b1c67fa2af5c0b9e4614d7d5e7f. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) 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 index 4f85d90f5f..7bacdde4c8 100644 --- 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 @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @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(); + .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(); } } From b8bcbeee90aa6b84778909ff94af60b5af78ebe2 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 1 Sep 2020 19:13:34 +0530 Subject: [PATCH 41/72] Added two space indent for the line continuation. --- .../configuration/SwaggerConfiguration.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) 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 index 7bacdde4c8..4f85d90f5f 100644 --- 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 @@ -30,10 +30,10 @@ public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); } /** @@ -43,21 +43,21 @@ public class SwaggerConfiguration { @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(); + .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(); } } From 2dc6089b10eb062009fde17d72d2a0352f3fc70d Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 1 Sep 2020 16:49:22 +0200 Subject: [PATCH 42/72] BAEL-4518: Upgrade jooq version (#9955) --- spring-jooq/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 From 468217efea75f9cc43f19fb5ca8f4fc2b65785a8 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Tue, 1 Sep 2020 17:19:24 +0200 Subject: [PATCH 43/72] JAVA-2398: Remove redundant config classes import --- .../com/baeldung/swagger2boot/configuration/SpringFoxConfig.java | 1 - 1 file changed, 1 deletion(-) 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 b404b0c2f8..5998ffeb2a 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 @@ -22,7 +22,6 @@ import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; @Configuration -@Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SpringFoxConfig { private ApiInfo apiInfo() { From 8d2c467e2b4205812fcaaa2140ac0318a657a91f Mon Sep 17 00:00:00 2001 From: majajoksovic Date: Tue, 1 Sep 2020 17:23:00 +0200 Subject: [PATCH 44/72] BAEL-4465 (#9954) * initial commit * fixed indent * removed unused dependencies * some minor code changes and unit tests * fixed file names --- libraries-security/pom.xml | 17 +++-- .../com/baeldung/ssh/apachesshd/SshdDemo.java | 64 +++++++++++++++++++ .../java/com/baeldung/ssh/jsch/JschDemo.java | 52 +++++++++++++++ .../baeldung/ssh/ApacheMinaSshdLiveTest.java | 38 +++++++++++ .../java/com/baeldung/ssh/JSchLiveTest.java | 35 ++++++++++ 5 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java create mode 100644 libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java create mode 100644 libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java create mode 100644 libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java 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); + } +} From 9d24bc15986325ca896e62cfd0bfd6f8c5048375 Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Tue, 1 Sep 2020 21:15:01 +0200 Subject: [PATCH 45/72] BAEL-4297: example of IllegalMonitorStateException --- .../exceptions/illegalmonitorstate/Data.java | 14 ++++ .../SynchronizedReceiver.java | 35 ++++++++++ .../SynchronizedSender.java | 33 +++++++++ .../UnSynchronizedReceiver.java | 33 +++++++++ .../UnSynchronizedSender.java | 31 ++++++++ .../IllegalMonitorStateExceptionUnitTest.java | 70 +++++++++++++++++++ 6 files changed, 216 insertions(+) create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java create mode 100644 core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java create mode 100644 core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java new file mode 100644 index 0000000000..b5867d15e7 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java @@ -0,0 +1,14 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class Data { + private String message; + + public void send(String message) { + this.message = message; + } + + public String receive() { + return message; + } +} + diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java new file mode 100644 index 0000000000..3dffb7b30a --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java @@ -0,0 +1,35 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class SynchronizedReceiver implements Runnable { + private final Data data; + private String message; + private boolean illegalMonitorStateExceptionOccurred; + + public SynchronizedReceiver(Data data) { + this.data = data; + } + + @Override + public void run() { + synchronized (data) { + try { + data.wait(); + this.message = data.receive(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + e.printStackTrace(); + illegalMonitorStateExceptionOccurred = true; + } + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } + + public String getMessage() { + return message; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java new file mode 100644 index 0000000000..04bac03e77 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java @@ -0,0 +1,33 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class SynchronizedSender implements Runnable { + private final Data data; + private boolean illegalMonitorStateExceptionOccurred; + + public SynchronizedSender(Data data) { + this.data = data; + } + + @Override + public void run() { + synchronized (data) { + try { + Thread.sleep(1000); + + data.send("test"); + + data.notifyAll(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + e.printStackTrace(); + illegalMonitorStateExceptionOccurred = true; + } + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java new file mode 100644 index 0000000000..a8e8befc4d --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java @@ -0,0 +1,33 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class UnSynchronizedReceiver implements Runnable { + private final Data data; + private String message; + private boolean illegalMonitorStateExceptionOccurred; + + public UnSynchronizedReceiver(Data data) { + this.data = data; + } + + @Override + public void run() { + try { + data.wait(); + this.message = data.receive(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + e.printStackTrace(); + illegalMonitorStateExceptionOccurred = true; + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } + + public String getMessage() { + return message; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java new file mode 100644 index 0000000000..eb6fa16649 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java @@ -0,0 +1,31 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class UnSynchronizedSender implements Runnable { + private final Data data; + private boolean illegalMonitorStateExceptionOccurred; + + public UnSynchronizedSender(Data data) { + this.data = data; + } + + @Override + public void run() { + try { + Thread.sleep(1000); + + data.send("test"); + + data.notifyAll(); + } catch (InterruptedException e) { + e.printStackTrace(); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + e.printStackTrace(); + illegalMonitorStateExceptionOccurred = true; + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java new file mode 100644 index 0000000000..800cdc4a7b --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class IllegalMonitorStateExceptionUnitTest { + + @Test + void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException { + Data data = new Data(); + + SynchronizedReceiver receiver = new SynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + SynchronizedSender sender = new SynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + senderThread.join(1000); + receiverThread.join(1000); + + assertEquals("test", receiver.getMessage()); + assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); + assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); + } + + @Test + void whenSyncSenderAndUnSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException { + Data data = new Data(); + + UnSynchronizedReceiver receiver = new UnSynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + SynchronizedSender sender = new SynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + + receiverThread.join(1000); + senderThread.join(1000); + + assertNull(receiver.getMessage()); + assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); + assertTrue(receiver.hasIllegalMonitorStateExceptionOccurred()); + } + + @Test + void whenUnSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldBeThrown() throws InterruptedException { + Data data = new Data(); + + SynchronizedReceiver receiver = new SynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + UnSynchronizedSender sender = new UnSynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + + receiverThread.join(1000); + senderThread.join(1000); + + assertNull(receiver.getMessage()); + assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); + assertTrue(sender.hasIllegalMonitorStateExceptionOccurred()); + } +} From 8d07e8fab96ca4375ae21c953f904d74985b4164 Mon Sep 17 00:00:00 2001 From: Sebastian Luna Date: Wed, 2 Sep 2020 07:46:50 -0500 Subject: [PATCH 46/72] BAEL-4387 Change module --- .../ArrayToListConversionUnitTest.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) rename {java-collections-conversions-2 => core-java-modules/core-java-string-operations-3}/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java (61%) diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java similarity index 61% rename from java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java rename to core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java index 551661810d..80e7b93b0c 100644 --- a/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java +++ b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java @@ -1,21 +1,24 @@ package com.baeldung.arrayconversion; +import org.hamcrest.CoreMatchers; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertArrayEquals; + public class ArrayToListConversionUnitTest { @Test(expected = UnsupportedOperationException.class) public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() { String[] stringArray = new String[] { "A", "B", "C", "D" }; List stringList = Arrays.asList(stringArray); - System.out.println(stringList); stringList.set(0, "E"); - System.out.println(stringList); - System.out.println(Arrays.toString(stringArray)); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); + assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" }); stringList.add("F"); } @@ -23,10 +26,10 @@ public class ArrayToListConversionUnitTest { public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() { String[] stringArray = new String[] { "A", "B", "C", "D" }; List stringList = new ArrayList<>(Arrays.asList(stringArray)); - System.out.println(stringList); stringList.set(0, "E"); - System.out.println(stringList); - System.out.println(Arrays.toString(stringArray)); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); + assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" }); stringList.add("F"); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F")); } } From c9d080aff4fbda963063d0abf6e5c86c5c524a1a Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 2 Sep 2020 15:23:35 +0200 Subject: [PATCH 47/72] JAVA-2401: Remove redundant repository config --- spring-boot-modules/spring-boot-mvc/pom.xml | 9 --------- 1 file changed, 9 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 39046ee6d9..560ea1cffa 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -17,15 +17,6 @@ spring-boot-mvc Module For Spring Boot MVC - - - - jcenter-release - jcenter - http://oss.jfrog.org/artifactory/oss-release-local/ - - - From 473b453a1f0bf2f46d00999a000a0e881df8df1d Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Wed, 2 Sep 2020 21:16:52 +0530 Subject: [PATCH 48/72] BAEL-4441: Custom User Attributes with Keycloak and Spring (#9966) --- .../keycloak/CustomUserAttrController.java | 46 +++++++++++++++++++ .../com/baeldung/keycloak/SecurityConfig.java | 2 +- .../main/resources/templates/userInfo.html | 15 ++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java create mode 100644 spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java new file mode 100644 index 0000000000..1959590e5a --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java @@ -0,0 +1,46 @@ +package com.baeldung.keycloak; + +import java.security.Principal; +import java.util.Map; + +import org.keycloak.KeycloakPrincipal; +import org.keycloak.KeycloakSecurityContext; +import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; +import org.keycloak.representations.IDToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CustomUserAttrController { + + @GetMapping(path = "/users") + public String getUserInfo(Model model) { + + KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) SecurityContextHolder.getContext() + .getAuthentication(); + + final Principal principal = (Principal) authentication.getPrincipal(); + + String dob = ""; + + if (principal instanceof KeycloakPrincipal) { + + KeycloakPrincipal kPrincipal = (KeycloakPrincipal) principal; + IDToken token = kPrincipal.getKeycloakSecurityContext() + .getIdToken(); + + Map customClaims = token.getOtherClaims(); + + if (customClaims.containsKey("DOB")) { + dob = String.valueOf(customClaims.get("DOB")); + } + } + + model.addAttribute("username", principal.getName()); + model.addAttribute("dob", dob); + return "userInfo"; + } + +} diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 4ecb62b6d4..895ac8c562 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -44,7 +44,7 @@ class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.authorizeRequests() - .antMatchers("/customers*") + .antMatchers("/customers*", "/users*") .hasRole("user") .anyRequest() .permitAll(); diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html new file mode 100644 index 0000000000..1446fe2124 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html @@ -0,0 +1,15 @@ + + + + + +
+

+ Hello, --name--. +

+

+ Your Date of Birth as per our records is . +

+
+ + From 0a24acf927ce6270a624a684de1601e46faecb6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Wed, 19 Aug 2020 19:44:49 +0200 Subject: [PATCH 49/72] [JAVA-2306] Fix - Added spring-data-jpa-query-2 to modules list --- persistence-modules/pom.xml | 1 + persistence-modules/spring-data-jpa-query-2/pom.xml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 522c281386..468d50b458 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -68,6 +68,7 @@ spring-data-jpa-enterprise spring-data-jpa-filtering spring-data-jpa-query + spring-data-jpa-query-2 spring-data-jpa-repo spring-data-jdbc diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index b9e5120543..22cd373c95 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-data-jpa-query + spring-data-jpa-query-2 spring-data-jpa-query-2 From 4e4ac650fa6b71fe9139a35b455950ccd00e2eb8 Mon Sep 17 00:00:00 2001 From: fdpro Date: Wed, 19 Aug 2020 20:18:54 +0200 Subject: [PATCH 50/72] [JAVA-2306] Moved articles from spring-persistence-simple * https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa went into spring-jpa-2 * https://www.baeldung.com/hibernate-5-spring went to spring-jpa-2 * https://www.baeldung.com/transaction-configuration-with-jpa-and-spring went to spring-jpa-2 * https://www.baeldung.com/persistence-layer-with-spring-and-hibernate went to spring-jpa-2 * https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics went to spring-jpa-2 * https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa went to spring-data-jpa-repo-2 * https://www.baeldung.com/spring-data-jpa-query went to spring-data-jpa-query-2 * https://www.baeldung.com/spring-jdbc-jdbctemplate moved to spring-jdbc * Removed spring-persistence-simple module as all articles have been moved --- .../{ => spring}/jdbc/BatchProcessing.java | 2 +- .../baeldung/{ => spring}/jdbc/Employee.java | 2 +- .../jdbc/joins/ArticleWithAuthor.java | 2 +- .../jdbc/joins/ArticleWithAuthorDAO.java | 2 +- .../jdbc/BatchProcessingLiveTest.java | 2 +- .../jdbc/JdbcDriverLoadingUnitTest.java | 2 +- .../{ => spring}/jdbc/JdbcLiveTest.java | 2 +- .../{ => spring}/jdbc/ResultSetLiveTest.java | 2 +- .../joins/ArticleWithAuthorDAOLiveTest.java | 2 +- persistence-modules/pom.xml | 3 +- .../baeldung/spring/data/jpa/query}/User.java | 39 +- .../data/jpa/query}/UserRepository.java | 80 +-- .../data/jpa/query}/UserRepositoryCustom.java | 4 +- .../spring-data-jpa-repo-2/pom.xml | 47 ++ .../data/persistence/repository}/Foo.java | 17 +- .../persistence/repository/FooService.java | 15 + .../data/persistence/repository/IFooDAO.java} | 6 +- .../persistence/repository/IFooService.java | 5 + .../repository}/PersistenceConfig.java | 15 +- .../src/main/resources/application.properties | 3 + .../src/main/resources/persistence.properties | 9 + .../src/main/resources/springDataConfig.xml} | 6 +- .../repository/FooServiceIntegrationTest.java | 21 + persistence-modules/spring-jdbc/pom.xml | 41 ++ .../jdbc/CustomSQLErrorCodeTranslator.java | 2 +- .../com/baeldung/spring}/jdbc/Employee.java | 2 +- .../baeldung/spring}/jdbc/EmployeeDAO.java | 2 +- .../spring}/jdbc/EmployeeRowMapper.java | 2 +- .../spring}/jdbc/config/SpringJdbcConfig.java | 10 +- .../src/main/resources/application.properties | 3 + .../src/main/resources/jdbc/schema.sql | 0 .../src/main/resources/jdbc/test-data.sql | 0 .../jdbc/EmployeeDAOIntegrationTest.java | 4 +- persistence-modules/spring-jpa-2/pom.xml | 35 ++ .../hibernate/bootstrap/BarHibernateDAO.java | 0 .../hibernate/bootstrap/HibernateConf.java | 2 +- .../hibernate/bootstrap/HibernateXMLConf.java | 0 .../hibernate/bootstrap/model/TestEntity.java | 0 .../dao/generics}/AbstractHibernateDao.java | 24 +- .../spring/dao/generics}/AbstractJpaDAO.java | 4 +- .../baeldung/spring/dao/generics}/Foo.java | 19 +- .../spring/dao/generics/FooService.java | 21 + .../dao/generics}/GenericHibernateDao.java | 6 +- .../spring/dao/generics}/GenericJpaDao.java | 6 +- .../spring/dao/generics/IFooService.java | 5 + .../spring/dao/generics/IGenericDao.java} | 6 +- .../hibernate/AbstractHibernateDao.java | 56 ++ .../com/baeldung/spring/hibernate/Foo.java | 42 ++ .../baeldung/spring/hibernate}/FooDao.java | 8 +- .../baeldung/spring/hibernate}/IFooDao.java | 8 +- .../jpa/guide}/PersistenceJPAConfig.java | 14 +- .../spring/transaction/FooService.java | 8 + .../src/main/resources/application.properties | 11 + .../resources/hibernate5Configuration.xml | 0 .../main/resources/persistence-h2.properties | 0 .../resources/persistence-jpa-config.xml} | 3 - .../resources/persistence-mysql.properties | 0 .../HibernateBootstrapIntegrationTest.java | 0 .../HibernateXMLBootstrapIntegrationTest.java | 0 .../autogenkey/config/PersistenceConfig.java | 2 +- .../MessageRepositoryJDBCTemplate.java | 2 +- .../MessageRepositorySimpleJDBCInsert.java | 2 +- .../jdbc/autogenkey/GetAutoGenKeyByJDBC.java | 8 +- .../baeldung/{ => spring}/jdbc/Employee.java | 2 +- .../{ => spring}/jdbc/EmployeeDAO.java | 2 +- .../jdbc/EmployeeDAOUnitTest.java | 2 +- .../spring-persistence-simple/.gitignore | 13 - .../spring-persistence-simple/README.md | 25 - .../spring-persistence-simple/pom.xml | 152 ----- .../baeldung/config/PersistenceConfig.java | 110 ---- .../java/com/baeldung/jpa/dao/FooDao.java | 17 - .../persistence/dao/common/AbstractDao.java | 14 - .../persistence/dao/common/IGenericDao.java | 7 - .../com/baeldung/persistence/model/Bar.java | 102 ---- .../persistence/service/FooService.java | 36 -- .../data/persistence/model/Possession.java | 86 --- .../repository/UserRepositoryCustomImpl.java | 52 -- .../data/persistence/service/IFooService.java | 11 - .../service/common/AbstractService.java | 56 -- .../persistence/service/impl/FooService.java | 38 -- .../main/java/com/baeldung/util/IDUtil.java | 33 -- .../src/main/resources/hibernate5Config.xml | 34 -- .../main/resources/jdbc/springJdbc-config.xml | 19 - .../src/main/resources/logback.xml | 19 - .../src/main/resources/stored_procedure.sql | 20 - ...oPaginationPersistenceIntegrationTest.java | 157 ----- .../FooServicePersistenceIntegrationTest.java | 69 --- .../FooServiceSortingIntegrationTest.java | 118 ---- ...eSortingWitNullsManualIntegrationTest.java | 64 -- .../service/FooStoredProceduresLiveTest.java | 123 ---- .../FooTransactionalUnitTest.java | 250 -------- .../PersistenceTransactionalTestConfig.java | 149 ----- .../repository/UserRepositoryCommon.java | 555 ------------------ .../UserRepositoryIntegrationTest.java | 35 -- ...ractServicePersistenceIntegrationTest.java | 256 -------- .../FooServicePersistenceIntegrationTest.java | 77 --- .../src/test/resources/.gitignore | 13 - 97 files changed, 436 insertions(+), 2926 deletions(-) rename persistence-modules/core-java-persistence/src/main/java/com/baeldung/{ => spring}/jdbc/BatchProcessing.java (99%) rename persistence-modules/core-java-persistence/src/main/java/com/baeldung/{ => spring}/jdbc/Employee.java (97%) rename persistence-modules/core-java-persistence/src/main/java/com/baeldung/{ => spring}/jdbc/joins/ArticleWithAuthor.java (96%) rename persistence-modules/core-java-persistence/src/main/java/com/baeldung/{ => spring}/jdbc/joins/ArticleWithAuthorDAO.java (98%) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/{ => spring}/jdbc/BatchProcessingLiveTest.java (98%) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/{ => spring}/jdbc/JdbcDriverLoadingUnitTest.java (98%) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/{ => spring}/jdbc/JdbcLiveTest.java (99%) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/{ => spring}/jdbc/ResultSetLiveTest.java (99%) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/{ => spring}/jdbc/joins/ArticleWithAuthorDAOLiveTest.java (99%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query}/User.java (89%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query}/UserRepository.java (65%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query}/UserRepositoryCustom.java (72%) create mode 100644 persistence-modules/spring-data-jpa-repo-2/pom.xml rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model => spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository}/Foo.java (85%) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java => spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java} (75%) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config => spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository}/PersistenceConfig.java (90%) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties rename persistence-modules/{spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml => spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml} (82%) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java create mode 100644 persistence-modules/spring-jdbc/pom.xml rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung => spring-jdbc/src/main/java/com/baeldung/spring}/jdbc/CustomSQLErrorCodeTranslator.java (95%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung => spring-jdbc/src/main/java/com/baeldung/spring}/jdbc/Employee.java (95%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung => spring-jdbc/src/main/java/com/baeldung/spring}/jdbc/EmployeeDAO.java (99%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung => spring-jdbc/src/main/java/com/baeldung/spring}/jdbc/EmployeeRowMapper.java (94%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung => spring-jdbc/src/main/java/com/baeldung/spring}/jdbc/config/SpringJdbcConfig.java (75%) create mode 100644 persistence-modules/spring-jdbc/src/main/resources/application.properties rename persistence-modules/{spring-persistence-simple => spring-jdbc}/src/main/resources/jdbc/schema.sql (100%) rename persistence-modules/{spring-persistence-simple => spring-jdbc}/src/main/resources/jdbc/test-data.sql (100%) rename persistence-modules/{spring-persistence-simple/src/test/java/com/baeldung => spring-jdbc/src/test/java/com/baeldung/spring}/jdbc/EmployeeDAOIntegrationTest.java (97%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java (100%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java (97%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java (100%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java (100%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics}/AbstractHibernateDao.java (87%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/jpa/dao => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics}/AbstractJpaDAO.java (96%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/persistence/model => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics}/Foo.java (82%) create mode 100644 persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics}/GenericHibernateDao.java (89%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics}/GenericJpaDao.java (80%) create mode 100644 persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java => spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java} (64%) create mode 100644 persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java create mode 100644 persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao => spring-jpa-2/src/main/java/com/baeldung/spring/hibernate}/FooDao.java (55%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/jpa/dao => spring-jpa-2/src/main/java/com/baeldung/spring/hibernate}/IFooDao.java (65%) rename persistence-modules/{spring-persistence-simple/src/main/java/com/baeldung/config => spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide}/PersistenceJPAConfig.java (91%) create mode 100644 persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java create mode 100644 persistence-modules/spring-jpa-2/src/main/resources/application.properties rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/resources/hibernate5Configuration.xml (100%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/resources/persistence-h2.properties (100%) rename persistence-modules/{spring-persistence-simple/src/main/resources/persistence.xml => spring-jpa-2/src/main/resources/persistence-jpa-config.xml} (89%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/main/resources/persistence-mysql.properties (100%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java (100%) rename persistence-modules/{spring-persistence-simple => spring-jpa-2}/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java (100%) rename persistence-modules/spring-jpa/src/main/java/com/baeldung/{ => spring}/jdbc/autogenkey/config/PersistenceConfig.java (94%) rename persistence-modules/spring-jpa/src/main/java/com/baeldung/{ => spring}/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java (92%) rename persistence-modules/spring-jpa/src/main/java/com/baeldung/{ => spring}/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java (90%) rename persistence-modules/spring-jpa/src/test/java/com/baeldung/{ => spring}/jdbc/autogenkey/GetAutoGenKeyByJDBC.java (79%) rename persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/{ => spring}/jdbc/Employee.java (95%) rename persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/{ => spring}/jdbc/EmployeeDAO.java (98%) rename persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/{ => spring}/jdbc/EmployeeDAOUnitTest.java (99%) delete mode 100644 persistence-modules/spring-persistence-simple/.gitignore delete mode 100644 persistence-modules/spring-persistence-simple/README.md delete mode 100644 persistence-modules/spring-persistence-simple/pom.xml delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java delete mode 100644 persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml delete mode 100644 persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml delete mode 100644 persistence-modules/spring-persistence-simple/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-persistence-simple/src/test/resources/.gitignore diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java similarity index 99% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java index ad6a064c98..51b27ef5f4 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.sql.*; import java.util.UUID; diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java similarity index 97% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java index 27aef8b82f..99e5a1ad4a 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.util.Objects; diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java similarity index 96% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java index 5ce196ee47..bbcbb5871e 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; class ArticleWithAuthor { diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java similarity index 98% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java index 55f03d99ec..48961b786f 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; import java.sql.Connection; import java.sql.ResultSet; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java similarity index 98% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java index c905482f55..3cb5e779f5 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import org.junit.Before; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java similarity index 98% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java index 387c050285..937cf1b833 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import static org.junit.Assert.*; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java index 81179aade9..c13f94f12a 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import org.apache.log4j.Logger; import org.junit.After; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java index 4e10f8bd43..853e78a68d 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import static org.junit.Assert.assertEquals; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java index 3f69a0e333..055c7ed9ed 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; import org.junit.After; import org.junit.Before; diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 468d50b458..1a5ca8df70 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -70,6 +70,7 @@ spring-data-jpa-query spring-data-jpa-query-2 spring-data-jpa-repo + spring-data-jpa-repo-2 spring-data-jdbc @@ -83,8 +84,8 @@ spring-hibernate4 spring-jpa spring-jpa-2 + spring-jdbc - spring-persistence-simple spring-persistence-simple-2 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java index 1475eccbf0..179dbf2ae7 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.model; +package com.baeldung.spring.data.jpa.query; import javax.persistence.*; import java.time.LocalDate; @@ -8,7 +8,6 @@ import java.util.Objects; @Entity @Table(name = "users") public class User { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @@ -28,9 +27,6 @@ public class User { private Integer status; - @OneToMany - List possessionList; - public User() { super(); } @@ -87,12 +83,20 @@ public class User { return creationDate; } - public List getPossessionList() { - return possessionList; + public LocalDate getLastLoginDate() { + return lastLoginDate; } - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; + public void setLastLoginDate(LocalDate lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; } @Override @@ -119,21 +123,4 @@ public class User { public int hashCode() { return Objects.hash(id, name, creationDate, age, email, status); } - - public LocalDate getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(LocalDate lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - } \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java similarity index 65% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java index a8e3a536c3..6547e0ef66 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.spring.data.jpa.query; -import com.baeldung.spring.data.persistence.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -9,51 +8,16 @@ import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import java.time.LocalDate; import java.util.Collection; import java.util.List; -import java.util.stream.Stream; public interface UserRepository extends JpaRepository, UserRepositoryCustom { - - Stream findAllByName(String name); - @Query("SELECT u FROM User u WHERE u.status = 1") Collection findAllActiveUsers(); - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - @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); @@ -63,6 +27,27 @@ public interface UserRepository extends JpaRepository, UserReposi @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) Page findAllUsersWithPaginationNative(Pageable pageable); + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @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 = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@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(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(value = "SELECT u FROM User u WHERE u.name IN :names") + List findUserByNameList(@Param("names") Collection names); + @Modifying @Query("update User u set u.status = :status where u.name = :name") int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @@ -74,25 +59,4 @@ public interface UserRepository extends JpaRepository, UserReposi @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) @Modifying void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java similarity index 72% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java index 77e661bbbe..a3e53528f7 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java @@ -1,6 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.model.User; +package com.baeldung.spring.data.jpa.query; import java.util.Collection; import java.util.List; diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml new file mode 100644 index 0000000000..855b441074 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + spring-data-jpa-repo-2 + spring-data-jpa-repo-2 + + + + + javax.persistence + javax.persistence-api + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + + com.google.guava + guava + ${guava.version} + + + + + 29.0-jre + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java similarity index 85% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java index 64bfe203d0..6833c4c556 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java @@ -1,16 +1,10 @@ -package com.baeldung.spring.data.persistence.model; +package com.baeldung.spring.data.persistence.repository; +import javax.persistence.*; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - @Entity public class Foo implements Serializable { - @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @@ -28,8 +22,6 @@ public class Foo implements Serializable { this.name = name; } - // API - public long getId() { return id; } @@ -46,8 +38,6 @@ public class Foo implements Serializable { this.name = name; } - // - @Override public int hashCode() { final int prime = 31; @@ -79,5 +69,4 @@ public class Foo implements Serializable { builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } - -} +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java new file mode 100644 index 0000000000..cb09a92b82 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.persistence.repository; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FooService implements IFooService { + @Autowired + private IFooDAO dao; + + @Override + public Foo create(Foo foo) { + return dao.save(foo); + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java similarity index 75% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java index 0b750e37e1..20a81e7bfa 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java @@ -1,13 +1,13 @@ package com.baeldung.spring.data.persistence.repository; -import com.baeldung.spring.data.persistence.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface IFooDao extends JpaRepository { +public interface IFooDAO extends JpaRepository { + + Foo findByName(String name); @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") Foo retrieveByName(@Param("name") String name); - } diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java new file mode 100644 index 0000000000..8ce6a2d1ae --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java @@ -0,0 +1,5 @@ +package com.baeldung.spring.data.persistence.repository; + +public interface IFooService { + Foo create(Foo foo); +} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java similarity index 90% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java index 604923d615..f73ea94658 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.config; +package com.baeldung.spring.data.persistence.repository; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; @@ -20,11 +20,11 @@ import javax.sql.DataSource; import java.util.Properties; @Configuration +@PropertySource("classpath:persistence.properties") +@ComponentScan("com.baeldung.spring.data.persistence.repository") +//@ImportResource("classpath*:*springDataConfig.xml") @EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) -@ComponentScan({ "com.baeldung.spring.data.persistence" }) -//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml") -@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository") +@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") public class PersistenceConfig { @Autowired @@ -38,7 +38,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan("com.baeldung.spring.data.persistence.model"); + em.setPackagesToScan("com.baeldung.spring.data.persistence.repository"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); @@ -78,5 +78,4 @@ public class PersistenceConfig { return hibernateProperties; } - -} \ No newline at end of file +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties new file mode 100644 index 0000000000..cb1eab9443 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties new file mode 100644 index 0000000000..339859a6e8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties @@ -0,0 +1,9 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.hbm2ddl.auto=create-drop +hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml similarity index 82% rename from persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml rename to persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml index 91778a17af..b2616d9eae 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml @@ -2,12 +2,10 @@ - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java new file mode 100644 index 0000000000..141844fa11 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.data.persistence.repository; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = PersistenceConfig.class) +public class FooServiceIntegrationTest { + + @Autowired + private IFooService service; + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } +} diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml new file mode 100644 index 0000000000..4ac5239318 --- /dev/null +++ b/persistence-modules/spring-jdbc/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + spring-jdbc + spring-jdbc + + + + org.springframework.data + spring-data-jdbc + ${spring-data-jdbc.version} + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + + + mysql + mysql-connector-java + runtime + + + + + 2.0.3.RELEASE + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java similarity index 95% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java index 48ddfb04b1..aa0ffde00c 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java similarity index 95% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java index a43eb265c7..84780e30da 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; public class Employee { private int id; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java similarity index 99% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java index eef085f386..a6d0fe2f3b 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java similarity index 94% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java index d09cd45dbc..bf55d6160d 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java similarity index 75% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java index ddc24e439f..d7eb039637 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.config; +package com.baeldung.spring.jdbc.config; import javax.sql.DataSource; @@ -10,12 +10,16 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration -@ComponentScan("com.baeldung.jdbc") +@ComponentScan("com.baeldung.spring.jdbc") public class SpringJdbcConfig { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build(); + return new EmbeddedDatabaseBuilder() + .setType(EmbeddedDatabaseType.H2) + .addScript("classpath:jdbc/schema.sql") + .addScript("classpath:jdbc/test-data.sql") + .build(); } // @Bean diff --git a/persistence-modules/spring-jdbc/src/main/resources/application.properties b/persistence-modules/spring-jdbc/src/main/resources/application.properties new file mode 100644 index 0000000000..2f09a522ba --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/springjdbc +spring.datasource.username=guest_user +spring.datasource.password=guest_password \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql rename to persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql rename to persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java similarity index 97% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java index 453656098a..10f47402be 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java @@ -1,9 +1,9 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.util.ArrayList; import java.util.List; -import com.baeldung.jdbc.config.SpringJdbcConfig; +import com.baeldung.spring.jdbc.config.SpringJdbcConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml index 08a1f0c6a3..1c21f6b98d 100644 --- a/persistence-modules/spring-jpa-2/pom.xml +++ b/persistence-modules/spring-jpa-2/pom.xml @@ -15,6 +15,17 @@ + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + org.springframework spring-orm @@ -43,8 +54,25 @@ h2 ${h2.version} + + org.apache.tomcat + tomcat-dbcp + ${tomcat-dbcp.version} + + + + + com.google.guava + guava + ${guava.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + org.springframework spring-test @@ -57,6 +85,13 @@ 5.1.5.RELEASE + + + 9.0.0.M26 + + + 21.0 + 2.2.6.RELEASE \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java similarity index 97% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java index 150e3778af..da23803d76 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java @@ -51,7 +51,7 @@ public class HibernateConf { return transactionManager; } - private final Properties hibernateProperties() { + private Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java similarity index 87% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java index e406f896dc..bd78fe647d 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java @@ -1,52 +1,49 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; +package com.baeldung.spring.dao.generics; +import com.google.common.base.Preconditions; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.common.base.Preconditions; +import java.io.Serializable; +import java.util.List; @SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { +public abstract class AbstractHibernateDao { + private Class clazz; @Autowired protected SessionFactory sessionFactory; - // API + public void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } - @Override + // API public T findOne(final long id) { return (T) getCurrentSession().get(clazz, id); } - @Override public List findAll() { return getCurrentSession().createQuery("from " + clazz.getName()).list(); } - @Override public T create(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().saveOrUpdate(entity); return entity; } - @Override public T update(final T entity) { Preconditions.checkNotNull(entity); return (T) getCurrentSession().merge(entity); } - @Override public void delete(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().delete(entity); } - @Override public void deleteById(final long entityId) { final T entity = findOne(entityId); Preconditions.checkState(entity != null); @@ -56,5 +53,4 @@ public abstract class AbstractHibernateDao extends Abstr protected Session getCurrentSession() { return sessionFactory.getCurrentSession(); } - } \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java similarity index 96% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java index a6542c5cb1..e68a9281a0 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jpa.dao; +package com.baeldung.spring.dao.generics; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @@ -6,7 +6,6 @@ import java.io.Serializable; import java.util.List; public abstract class AbstractJpaDAO { - private Class clazz; @PersistenceContext(unitName = "entityManagerFactory") @@ -42,5 +41,4 @@ public abstract class AbstractJpaDAO { final T entity = findOne(entityId); delete(entity); } - } \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java similarity index 82% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java index 009876f8cb..7849abb25f 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java @@ -1,21 +1,10 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Cacheable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedNativeQueries; -import javax.persistence.NamedNativeQuery; +package com.baeldung.spring.dao.generics; import org.hibernate.annotations.CacheConcurrencyStrategy; +import javax.persistence.*; +import java.io.Serializable; + @Entity @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java new file mode 100644 index 0000000000..4c2014c717 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.dao.generics; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FooService implements IFooService { + + IGenericDao dao; + + @Autowired + public void setDao(IGenericDao daoToSet) { + dao = daoToSet; + dao.setClazz(Foo.class); + } + + @Override + public Foo retrieveByName(String name) { + return null; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java index 18b16fa033..619a144176 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java @@ -1,11 +1,11 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; +package com.baeldung.spring.dao.generics; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; +import java.io.Serializable; + @Repository @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao { diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java similarity index 80% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java index d4da194f4d..cf89b05f96 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java @@ -1,12 +1,10 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; +package com.baeldung.spring.dao.generics; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; -import com.baeldung.jpa.dao.AbstractJpaDAO; +import java.io.Serializable; @Repository @Scope(BeanDefinition.SCOPE_PROTOTYPE) diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java new file mode 100644 index 0000000000..2d525de405 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java @@ -0,0 +1,5 @@ +package com.baeldung.spring.dao.generics; + +public interface IFooService { + Foo retrieveByName(String name); +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java similarity index 64% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java index 34c5e0f616..3fd7baf63f 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java @@ -1,9 +1,10 @@ -package com.baeldung.persistence.dao.common; +package com.baeldung.spring.dao.generics; import java.io.Serializable; import java.util.List; -public interface IOperations { +public interface IGenericDao { + void setClazz(Class< T > clazzToSet); T findOne(final long id); @@ -16,5 +17,4 @@ public interface IOperations { void delete(final T entity); void deleteById(final long entityId); - } diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java new file mode 100644 index 0000000000..c0a99e92c8 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.hibernate; + +import com.google.common.base.Preconditions; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.Serializable; +import java.util.List; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao { + private Class clazz; + + @Autowired + protected SessionFactory sessionFactory; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } + + // API + public T findOne(final long id) { + return (T) getCurrentSession().get(clazz, id); + } + + public List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).list(); + } + + public T create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().saveOrUpdate(entity); + return entity; + } + + public T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + public void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + public void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java new file mode 100644 index 0000000000..f92b510071 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.hibernate; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Foo implements Serializable { + private static final long serialVersionUID = 1L; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + @Column(name = "NAME") + private String name; + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java similarity index 55% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java index 67c10fe7fe..d5495d4eb1 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java @@ -1,14 +1,9 @@ -package com.baeldung.hibernate.dao; +package com.baeldung.spring.hibernate; -import com.baeldung.persistence.model.Foo; import org.springframework.stereotype.Repository; -import com.baeldung.jpa.dao.IFooDao; -import com.baeldung.persistence.dao.common.AbstractHibernateDao; - @Repository public class FooDao extends AbstractHibernateDao implements IFooDao { - public FooDao() { super(); @@ -16,5 +11,4 @@ public class FooDao extends AbstractHibernateDao implements IFooDao { } // API - } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java similarity index 65% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java index 8140c56edd..d397163be5 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java @@ -1,21 +1,15 @@ -package com.baeldung.jpa.dao; +package com.baeldung.spring.hibernate; import java.util.List; -import com.baeldung.persistence.model.Foo; - public interface IFooDao { - Foo findOne(long id); List findAll(); - Foo create(Foo entity); - Foo update(Foo entity); void delete(Foo entity); void deleteById(long entityId); - } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java similarity index 91% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java index e8a2aefd6b..497d735c10 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java @@ -1,9 +1,8 @@ -package com.baeldung.config; +package com.baeldung.spring.jpa.guide; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @@ -21,17 +20,12 @@ import java.util.Properties; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) +@PropertySource("classpath:persistence-h2.properties") public class PersistenceJPAConfig { @Autowired private Environment env; - public PersistenceJPAConfig() { - super(); - } - // beans @Bean @@ -75,9 +69,7 @@ public class PersistenceJPAConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); - - + return hibernateProperties; } - } \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java new file mode 100644 index 0000000000..407d8e3394 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.transaction; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FooService {} \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-jpa-2/src/main/resources/application.properties new file mode 100644 index 0000000000..0270c1683e --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/resources/application.properties @@ -0,0 +1,11 @@ +# H2 +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 + +# MySQL +#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +#spring.datasource.username=mysqluser +#spring.datasource.password=mysqlpass +#spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml rename to persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml index 57687c306d..54774442c6 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml @@ -6,7 +6,6 @@ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - @@ -14,8 +13,6 @@ - diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java similarity index 94% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java index 99f50abf4c..d1f8864357 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.config; +package com.baeldung.spring.jdbc.autogenkey.config; import javax.sql.DataSource; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java similarity index 92% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java index cf0dbe4681..0f47473bd7 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.repository; +package com.baeldung.spring.jdbc.autogenkey.repository; import java.sql.PreparedStatement; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java rename to persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java index 022ea29ed6..247fbf28c2 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java +++ b/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.repository; +package com.baeldung.spring.jdbc.autogenkey.repository; import java.util.HashMap; import java.util.Map; diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java similarity index 79% rename from persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java rename to persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index aa4d061997..f0ad853c2a 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey; +package com.baeldung.spring.jdbc.autogenkey; import static org.junit.Assert.assertEquals; @@ -9,14 +9,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; +import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; +import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; @RunWith(SpringRunner.class) public class GetAutoGenKeyByJDBC { @Configuration - @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey" }) + @ComponentScan(basePackages = {"com.baeldung.spring.jdbc.autogenkey"}) public static class SpringConfig { } diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java similarity index 95% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java index bd6fe0fb15..adc2255ca4 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; public class Employee { private int id; diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java similarity index 98% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java rename to persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java index 2ea42381eb..6e2ad9682d 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.util.ArrayList; import java.util.Collections; diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java similarity index 99% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java rename to persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java index 369725bafd..bbc688293b 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java +++ b/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/persistence-modules/spring-persistence-simple/.gitignore b/persistence-modules/spring-persistence-simple/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/persistence-modules/spring-persistence-simple/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md deleted file mode 100644 index d665433eef..0000000000 --- a/persistence-modules/spring-persistence-simple/README.md +++ /dev/null @@ -1,25 +0,0 @@ -========= - -## Spring Persistence Example Project - - -### Relevant Articles: -- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) -- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) -- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) -- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) -- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml deleted file mode 100644 index 7318ec55bd..0000000000 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - 4.0.0 - spring-persistence-simple - 0.1-SNAPSHOT - spring-persistence-simple - - - com.baeldung - persistence-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework - spring-orm - ${org.springframework.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-aspects - ${org.springframework.version} - - - - org.hibernate - hibernate-core - ${hibernate.version} - - - javax.transaction - jta - ${jta.version} - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - mysql - mysql-connector-java - ${mysql-connector-java.version} - runtime - - - org.springframework.data - spring-data-jpa - ${spring-data-jpa.version} - - - com.h2database - h2 - ${h2.version} - - - - org.apache.tomcat - tomcat-dbcp - ${tomcat-dbcp.version} - - - - - - com.google.guava - guava - ${guava.version} - - - org.assertj - assertj-core - ${assertj.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - com.querydsl - querydsl-jpa - ${querydsl.version} - - - com.querydsl - querydsl-apt - ${querydsl.version} - - - - - - - com.mysema.maven - apt-maven-plugin - ${apt-maven-plugin.version} - - - generate-sources - - process - - - target/generated-sources - com.querydsl.apt.jpa.JPAAnnotationProcessor - - - - - - - - - - 5.2.6.RELEASE - - - 5.4.13.Final - 8.0.19 - 1.4.200 - 2.2.7.RELEASE - 9.0.0.M26 - 1.1 - 4.2.1 - - - 21.0 - 3.8.0 - 1.1.3 - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java deleted file mode 100644 index cdddbaa787..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.persistence.service.FooService; -import com.google.common.base.Preconditions; -import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import org.springframework.orm.hibernate5.HibernateTransactionManager; -import org.springframework.orm.hibernate5.LocalSessionFactoryBean; -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 org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@EnableTransactionManagement -@EnableJpaAuditing -@PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan("com.baeldung.persistence.model"); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(restDataSource()); - emf.setPackagesToScan("com.baeldung.persistence.model"); - - final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - emf.setJpaVendorAdapter(vendorAdapter); - emf.setJpaProperties(hibernateProperties()); - - return emf; - } - - @Bean - public DataSource restDataSource() { - final BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager hibernateTransactionManager() { - final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); - transactionManager.setSessionFactory(sessionFactory().getObject()); - return transactionManager; - } - - @Bean - public PlatformTransactionManager jpaTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - @Bean - public FooService fooService() { - return new FooService(); - } - - private Properties hibernateProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "true"); - - // Envers properties - hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); - - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java deleted file mode 100644 index e79a44a0c2..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jpa.dao; - -import com.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractJpaDAO implements IFooDao { - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java deleted file mode 100644 index 5a6c76a93a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; - -import com.google.common.base.Preconditions; - -public abstract class AbstractDao implements IOperations { - - protected Class clazz; - - protected final void setClazz(final Class clazzToSet) { - clazz = Preconditions.checkNotNull(clazzToSet); - } -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java deleted file mode 100644 index 8d8af18394..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; - -public interface IGenericDao extends IOperations { - // -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java deleted file mode 100644 index 5a88ecc6cf..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; - -@Entity -public class Bar implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @OrderBy("name ASC") - List fooList; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - this.name = name; - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public List getFooList() { - return fooList; - } - - public void setFooList(final List fooList) { - this.fooList = fooList; - } - - // - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Bar other = (Bar) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java deleted file mode 100644 index efe9743670..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import com.baeldung.jpa.dao.IFooDao; -import com.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - public void create(final Foo entity) { - dao.create(entity); - } - - public Foo findOne(final long id) { - return dao.findOne(id); - } - - public List findAll() { - return dao.findAll(); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java deleted file mode 100644 index 44ca9fc62e..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.spring.data.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table -public class Possession { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public Possession() { - super(); - } - - public Possession(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Possession other = (Possession) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java deleted file mode 100644 index 366b2c54d0..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.model.User; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.*; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class UserRepositoryCustomImpl implements UserRepositoryCustom { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findUserByEmails(Set emails) { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(User.class); - Root user = query.from(User.class); - - Path emailPath = user.get("email"); - - List predicates = new ArrayList<>(); - for (String email : emails) { - - predicates.add(cb.like(emailPath, email)); - - } - query.select(user) - .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); - - return entityManager.createQuery(query) - .getResultList(); - } - - @Override - public List findAllUsersByPredicates(Collection> predicates) { - List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); - Stream allUsersStream = allUsers.stream(); - for (java.util.function.Predicate predicate : predicates) { - allUsersStream = allUsersStream.filter(predicate); - } - - return allUsersStream.collect(Collectors.toList()); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java deleted file mode 100644 index 00e7ac01e4..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -import com.baeldung.spring.data.persistence.model.Foo; - -import com.baeldung.persistence.dao.common.IOperations; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java deleted file mode 100644 index 61c7d6fcaa..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.spring.data.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.persistence.dao.common.IOperations; -import com.google.common.collect.Lists; - -@Transactional -public abstract class AbstractService implements IOperations { - - // read - one - - @Override - @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - // read - all - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - // write - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(long entityId) { - T entity = findOne(entityId); - delete(entity); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java deleted file mode 100644 index c1406b8602..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.spring.data.persistence.service.impl; - - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.spring.data.persistence.repository.IFooDao; -import com.baeldung.spring.data.persistence.service.IFooService; -import com.baeldung.spring.data.persistence.service.common.AbstractService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService extends AbstractService implements IFooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected PagingAndSortingRepository getDao() { - return dao; - } - - // custom methods - - @Override - public Foo retrieveByName(final String name) { - return dao.retrieveByName(name); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java deleted file mode 100644 index 45e72e046d..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.util; - -import java.util.Random; - -public final class IDUtil { - - private IDUtil() { - throw new AssertionError(); - } - - // API - - public static String randomPositiveLongAsString() { - return Long.toString(randomPositiveLong()); - } - - public static String randomNegativeLongAsString() { - return Long.toString(randomNegativeLong()); - } - - public static long randomPositiveLong() { - long id = new Random().nextLong() * 10000; - id = (id < 0) ? (-1 * id) : id; - return id; - } - - private static long randomNegativeLong() { - long id = new Random().nextLong() * 10000; - id = (id > 0) ? (-1 * id) : id; - return id; - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml deleted file mode 100644 index 55546a862a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml deleted file mode 100644 index e3d7452eb1..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml b/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml deleted file mode 100644 index ec0dc2469a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql deleted file mode 100644 index 9cedb75c37..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql +++ /dev/null @@ -1,20 +0,0 @@ -DELIMITER // - CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255)) - LANGUAGE SQL - DETERMINISTIC - SQL SECURITY DEFINER - BEGIN - SELECT * FROM foo WHERE name = fooName; - END // -DELIMITER ; - - -DELIMITER // - CREATE PROCEDURE GetAllFoos() - LANGUAGE SQL - DETERMINISTIC - SQL SECURITY DEFINER - BEGIN - SELECT * FROM foo; - END // -DELIMITER ; \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java deleted file mode 100644 index fbda459d65..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooPaginationPersistenceIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private FooService fooService; - - @Before - public final void before() { - final int minimalNumberOfEntities = 25; - if (fooService.findAll().size() <= minimalNumberOfEntities) { - for (int i = 0; i < minimalNumberOfEntities; i++) { - fooService.create(new Foo(randomAlphabetic(6))); - } - } - } - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() { - final int pageSize = 10; - - final Query query = entityManager.createQuery("From Foo"); - configurePagination(query, 1, pageSize); - - // When - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() { - final int pageSize = 10; - final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f"); - final long countResult = (long) queryTotal.getSingleResult(); - - final Query query = entityManager.createQuery("Select f from Foo as f order by f.id"); - final int lastPage = (int) ((countResult / pageSize) + 1); - configurePagination(query, lastPage, pageSize); - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(lessThan(pageSize + 1))); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() { - final int pageSize = 10; - - final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name"); - final List fooIds = queryIds.getResultList(); - - final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids"); - query.setParameter("ids", fooIds.subList(0, pageSize)); - - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @Test - public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() { - final int pageSize = 10; - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - final TypedQuery typedQuery = entityManager.createQuery(select); - typedQuery.setFirstResult(0); - typedQuery.setMaxResults(pageSize); - final List fooList = typedQuery.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @Test - public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() { - int pageNumber = 1; - final int pageSize = 10; - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class); - countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class))); - final Long count = entityManager.createQuery(countQuery).getSingleResult(); - - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - - TypedQuery typedQuery; - while (pageNumber < count.intValue()) { - typedQuery = entityManager.createQuery(select); - typedQuery.setFirstResult(pageNumber - 1); - typedQuery.setMaxResults(pageSize); - System.out.println("Current page: " + typedQuery.getResultList()); - pageNumber += pageSize; - } - - } - - // UTIL - - final int determineLastPage(final int pageSize, final long countResult) { - return (int) (countResult / pageSize) + 1; - } - - final void configurePagination(final Query query, final int pageNumber, final int pageSize) { - query.setFirstResult((pageNumber - 1) * pageSize); - query.setMaxResults(pageSize); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index f4b70a7fde..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooServicePersistenceIntegrationTest { - - @Autowired - private FooService service; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Foo(randomAlphabetic(6))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - @Test(expected = DataAccessException.class) - public final void temp_whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @Test - public final void whenEntityIsCreated_thenFound() { - final Foo fooEntity = new Foo("abc"); - service.create(fooEntity); - final Foo found = service.findOne(fooEntity.getId()); - Assert.assertNotNull(found); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java deleted file mode 100644 index c3db45ab41..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -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.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -@SuppressWarnings("unchecked") -public class FooServiceSortingIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - // tests - - @Test - public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() { - final String jql = "Select f from Foo as f order by f.id"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() { - final String jql = "Select f from Foo as f order by f.id desc"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingByTwoAttributes_thenPrintSortedResult() { - final String jql = "Select f from Foo as f order by f.name asc, f.id desc"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingFooByBar_thenBarsSorted() { - final String jql = "Select f from Foo as f order by f.name, f.bar.id"; - final Query barJoinQuery = entityManager.createQuery(jql); - final List fooList = barJoinQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - if (foo.getBar() != null) { - System.out.print("-------BarId:" + foo.getBar().getId()); - } - } - } - - @Test - public final void whenSortinfBar_thenPrintBarsSortedWithFoos() { - final String jql = "Select b from Bar as b order by b.id"; - final Query barQuery = entityManager.createQuery(jql); - final List barList = barQuery.getResultList(); - for (final Bar bar : barList) { - System.out.println("Bar Id:" + bar.getId()); - for (final Foo foo : bar.getFooList()) { - System.out.println("FooName:" + foo.getName()); - } - } - } - - @Test - public final void whenSortingFooWithCriteria_thenPrintSortedFoos() { - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); - final TypedQuery typedQuery = entityManager.createQuery(select); - final List fooList = typedQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() { - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id"))); - final TypedQuery typedQuery = entityManager.createQuery(select); - final List fooList = typedQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java deleted file mode 100644 index 103321fc64..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNull; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooServiceSortingWitNullsManualIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private FooService service; - - // tests - - @SuppressWarnings("unchecked") - @Test - public final void whenSortingByStringNullLast_thenLastNull() { - service.create(new Foo()); - service.create(new Foo(randomAlphabetic(6))); - - final String jql = "Select f from Foo as f order by f.name desc NULLS LAST"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - assertNull(fooList.get(fooList.toArray().length - 1).getName()); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - } - } - - @SuppressWarnings("unchecked") - @Test - public final void whenSortingByStringNullFirst_thenFirstNull() { - service.create(new Foo()); - - final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - assertNull(fooList.get(0).getName()); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - } - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java deleted file mode 100644 index 32a94ea3cb..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import com.baeldung.config.PersistenceConfig; -import com.baeldung.persistence.model.Foo; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.exception.SQLGrammarException; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooStoredProceduresLiveTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class); - - @Autowired - private SessionFactory sessionFactory; - - @Autowired - private FooService fooService; - - private Session session; - - @Before - public final void before() { - session = sessionFactory.openSession(); - Assume.assumeTrue(getAllFoosExists()); - Assume.assumeTrue(getFoosByNameExists()); - } - - private boolean getFoosByNameExists() { - try { - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); - return false; - } - } - - private boolean getAllFoosExists() { - try { - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); - return false; - } - } - - @After - public final void after() { - session.close(); - } - - @Test - public final void getAllFoosUsingStoredProcedures() { - - fooService.create(new Foo(randomAlphabetic(6))); - - // Stored procedure getAllFoos using createSQLQuery - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - List allFoos = sqlQuery.list(); - for (Foo foo : allFoos) { - LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); - } - assertEquals(allFoos.size(), fooService.findAll().size()); - - // Stored procedure getAllFoos using a Named Query - @SuppressWarnings("unchecked") - Query namedQuery = session.getNamedQuery("callGetAllFoos"); - List allFoos2 = namedQuery.list(); - for (Foo foo : allFoos2) { - LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); - } - assertEquals(allFoos2.size(), fooService.findAll().size()); - } - - @Test - public final void getFoosByNameUsingStoredProcedures() { - - fooService.create(new Foo("NewFooName")); - - // Stored procedure getFoosByName using createSQLQuery() - @SuppressWarnings("unchecked") - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); - List allFoosByName = sqlQuery.list(); - for (Foo foo : allFoosByName) { - LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); - } - - // Stored procedure getFoosByName using getNamedQuery() - @SuppressWarnings("unchecked") - Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); - List allFoosByName2 = namedQuery.list(); - for (Foo foo : allFoosByName2) { - LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); - } - - } -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java deleted file mode 100644 index 6f2a499bc5..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.baeldung.persistence.service.transactional; - -import com.baeldung.persistence.model.Foo; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; -import org.springframework.stereotype.Service; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.transaction.IllegalTransactionStateException; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionTemplate; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTransactionalTestConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooTransactionalUnitTest { - - static abstract class BasicFooDao { - @PersistenceContext private EntityManager entityManager; - - public Foo findOne(final long id) { - return entityManager.find(Foo.class, id); - } - - public Foo create(final Foo entity) { - entityManager.persist(entity); - return entity; - } - } - - @Repository - static class RequiredTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.REQUIRED) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class RequiresNewTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class SupportTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.SUPPORTS) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class MandatoryTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.MANDATORY) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class SupportTransactionalFooService { - @Transactional(propagation = Propagation.SUPPORTS) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class MandatoryTransactionalFooService { - @Transactional(propagation = Propagation.MANDATORY) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class NotSupportedTransactionalFooService { - @Transactional(propagation = Propagation.NOT_SUPPORTED) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class NeverTransactionalFooService { - @Transactional(propagation = Propagation.NEVER) - public Foo identity(Foo entity) { - return entity; - } - } - - @Autowired private TransactionTemplate transactionTemplate; - - @Autowired private RequiredTransactionalFooDao requiredTransactionalFooDao; - - @Autowired private RequiresNewTransactionalFooDao requiresNewTransactionalFooDao; - - @Autowired private SupportTransactionalFooDao supportTransactionalFooDao; - - @Autowired private MandatoryTransactionalFooDao mandatoryTransactionalFooDao; - - @Autowired private MandatoryTransactionalFooService mandatoryTransactionalFooService; - - @Autowired private NeverTransactionalFooService neverTransactionalFooService; - - @Autowired private NotSupportedTransactionalFooService notSupportedTransactionalFooService; - - @Autowired private SupportTransactionalFooService supportTransactionalFooService; - - @After - public void tearDown(){ - PersistenceTransactionalTestConfig.clearSpy(); - } - - @Test - public void givenRequiredWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { - requiredTransactionalFooDao.create(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - - - @Test - public void givenRequiresNewWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { - requiresNewTransactionalFooDao.create(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - supportTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test(expected = IllegalTransactionStateException.class) - public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { - mandatoryTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenNotSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - notSupportedTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenNeverWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - neverTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenRequiredWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return requiredTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenRequiresNewWithActiveTransaction_whenCallCreate_thenExpect1NewAnd1Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return requiresNewTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(1, transactionSpy.getSuspend()); - Assert.assertEquals(2, transactionSpy.getCreate()); - } - - @Test - public void givenSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return supportTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenMandatoryWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return mandatoryTransactionalFooDao.create(foo); - }); - - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenNotSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd1Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return notSupportedTransactionalFooService.identity(foo); - }); - - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(1, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test(expected = IllegalTransactionStateException.class) - public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return neverTransactionalFooService.identity(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java deleted file mode 100644 index 72031a2232..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.baeldung.persistence.service.transactional; - -import com.google.common.base.Preconditions; -import java.util.Properties; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -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 org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.support.DefaultTransactionStatus; -import org.springframework.transaction.support.TransactionSynchronizationAdapter; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) -@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao") -public class PersistenceTransactionalTestConfig { - - public static class TransactionSynchronizationAdapterSpy extends TransactionSynchronizationAdapter { - private int create, suspend; - - public int getSuspend() { - return suspend; - } - - public int getCreate() { - return create; - } - - public void create() { - create++; - } - - @Override - public void suspend() { - suspend++; - super.suspend(); - } - } - - - public static class JpaTransactionManagerSpy extends JpaTransactionManager { - @Override - protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) { - super.prepareSynchronization(status, definition); - if (status.isNewTransaction()) { - if ( adapterSpyThreadLocal.get() == null ){ - TransactionSynchronizationAdapterSpy spy = new TransactionSynchronizationAdapterSpy(); - TransactionSynchronizationManager.registerSynchronization(spy); - adapterSpyThreadLocal.set(spy); - } - adapterSpyThreadLocal.get().create(); - } - } - } - - private static ThreadLocal adapterSpyThreadLocal = new ThreadLocal<>(); - - @Autowired - private Environment env; - - public PersistenceTransactionalTestConfig() { - super(); - } - - public static TransactionSynchronizationAdapterSpy getSpy(){ - if ( adapterSpyThreadLocal.get() == null ) - return new TransactionSynchronizationAdapterSpy(); - return adapterSpyThreadLocal.get(); - } - - public static void clearSpy(){ - adapterSpyThreadLocal.set(null); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - - final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - - - @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManagerSpy transactionManager = new JpaTransactionManagerSpy(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); - return hibernateProperties; - } - - - @Bean - public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager){ - TransactionTemplate template = new TransactionTemplate(transactionManager); - template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); - return template; - } - - -} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java deleted file mode 100644 index 13b5b4357d..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java +++ /dev/null @@ -1,555 +0,0 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class UserRepositoryCommon { - - final String USER_EMAIL = "email@example.com"; - final String USER_EMAIL2 = "email2@example.com"; - final String USER_EMAIL3 = "email3@example.com"; - final String USER_EMAIL4 = "email4@example.com"; - final Integer INACTIVE_STATUS = 0; - final Integer ACTIVE_STATUS = 1; - final String USER_EMAIL5 = "email5@example.com"; - final String USER_EMAIL6 = "email6@example.com"; - final String USER_NAME_ADAM = "Adam"; - final String USER_NAME_PETER = "Peter"; - - @Autowired - protected UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(Sort.by("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo(USER_NAME_PETER); - } - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { - - User user1 = new User(); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - Set emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindByNameListReturnCollection() { - - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); - - List usersWithNames = userRepository.findUserByNameList(names); - - assertThat(usersWithNames.size()).isEqualTo(2); - } - - - @Test - @Transactional - public void whenInsertedWithQuery_ThenUserIsPersisted() { - userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); - userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); - - User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); - User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); - - assertThat(userAdam).isNotNull(); - assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); - assertThat(userPeter).isNotNull(); - assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); - } - - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - System.out.println(TimeZone.getDefault()); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index c76e345fdd..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.model.User; -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.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class UserRepositoryIntegrationTest extends UserRepositoryCommon { - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java deleted file mode 100644 index 2bccada9fe..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.util.IDUtil; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataAccessException; - -import com.baeldung.persistence.dao.common.IOperations; - -public abstract class AbstractServicePersistenceIntegrationTest { - - // tests - - // find - one - - @Test - /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { - // When - final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); - - // Then - assertNull(createdResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { - final Foo existingResource = persistNewEntity(); - getApi().findOne(existingResource.getId()); - } - - @Test - public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { - getApi().findOne(IDUtil.randomPositiveLong()); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertNotNull(retrievedResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertEquals(existingResource, retrievedResource); - } - - // find - one - by name - - // find - all - - @Test - /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { - getApi().findAll(); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { - final List resources = getApi().findAll(); - - assertNotNull(resources); - } - - @Test - /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - assertThat(allResources, not(Matchers. empty())); - } - - @Test - /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { - final Foo existingResource = persistNewEntity(); - - final List resources = getApi().findAll(); - - assertThat(resources, hasItem(existingResource)); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - for (final Foo resource : allResources) { - assertNotNull(resource.getId()); - } - } - - // create - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsCreated_thenException() { - getApi().create(null); - } - - @Test - /**/public void whenResourceIsCreated_thenNoExceptions() { - persistNewEntity(); - } - - @Test - /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { - final Foo existingResource = persistNewEntity(); - - assertNotNull(getApi().findOne(existingResource.getId())); - } - - @Test - /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { - final Foo originalResource = createNewEntity(); - final Foo savedResource = getApi().create(originalResource); - - assertEquals(originalResource, savedResource); - } - - @Test(expected = RuntimeException.class) - public void whenResourceWithFailedConstraintsIsCreated_thenException() { - final Foo invalidResource = createNewEntity(); - invalidate(invalidResource); - - getApi().create(invalidResource); - } - - /** - * -- specific to the persistence engine - */ - @Test(expected = DataAccessException.class) - @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") - public void whenResourceWithIdIsCreated_thenDataAccessException() { - final Foo resourceWithId = createNewEntity(); - resourceWithId.setId(IDUtil.randomPositiveLong()); - - getApi().create(resourceWithId); - } - - // update - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsUpdated_thenException() { - getApi().update(null); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - getApi().update(existingResource); - } - - /** - * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException - */ - @Test(expected = RuntimeException.class) - public void whenResourceIsUpdatedWithFailedConstraints_thenException() { - final Foo existingResource = persistNewEntity(); - invalidate(existingResource); - - getApi().update(existingResource); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - change(existingResource); - getApi().update(existingResource); - - final Foo updatedResource = getApi().findOne(existingResource.getId()); - - // Then - assertEquals(existingResource, updatedResource); - } - - // delete - - // @Test(expected = RuntimeException.class) - // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { - // // When - // getApi().delete(IDUtil.randomPositiveLong()); - // } - // - // @Test(expected = RuntimeException.class) - // public void whenResourceIsDeletedByNegativeId_thenException() { - // // When - // getApi().delete(IDUtil.randomNegativeLong()); - // } - // - // @Test - // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // } - // - // @Test - // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // - // // Then - // assertNull(getApi().findOne(existingResource.getId())); - // } - - // template method - - protected Foo createNewEntity() { - return new Foo(randomAlphabetic(6)); - } - - protected abstract IOperations getApi(); - - private final void invalidate(final Foo entity) { - entity.setName(null); - } - - private final void change(final Foo entity) { - entity.setName(randomAlphabetic(6)); - } - - protected Foo persistNewEntity() { - return getApi().create(createNewEntity()); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 8f628c5615..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.dao.common.IOperations; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { - - @Autowired - private IFooService service; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Foo(randomAlphabetic(6))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - // custom Query method - - @Test - public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { - final String name = randomAlphabetic(6); - service.create(new Foo(name)); - - final Foo retrievedByName = service.retrieveByName(name); - assertNotNull(retrievedByName); - } - - // work in progress - - @Test(expected = InvalidDataAccessApiUsageException.class) - @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - // API - - @Override - protected final IOperations getApi() { - return service; - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore b/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file From eb4c3064512dd995d4ea0fe414ef564531df600d Mon Sep 17 00:00:00 2001 From: fdpro Date: Sun, 30 Aug 2020 15:59:35 +0200 Subject: [PATCH 51/72] [JAVA-2306] Moved articles from spring-persistence-simple-2 * https://www.baeldung.com/spring-jdbctemplate-testing went to spring-jdbc * https://www.baeldung.com/spring-jdbctemplate-in-list went to spring-jdbc * https://www.baeldung.com/spring-mock-jndi-datasource went to spring-persistence-simple * Deleted spring-persistence-simple-2 module as all articles have been moved --- persistence-modules/pom.xml | 2 +- .../guide}/CustomSQLErrorCodeTranslator.java | 2 +- .../jdbc/{ => template/guide}/Employee.java | 2 +- .../{ => template/guide}/EmployeeDAO.java | 2 +- .../guide}/EmployeeRowMapper.java | 2 +- .../guide}/config/SpringJdbcConfig.java | 6 +- .../jdbc/template/inclause/Employee.java | 42 ++++++++++++++ .../jdbc/template/inclause}/EmployeeDAO.java | 28 ++++------ .../jdbc/template/testing}/Employee.java | 2 +- .../jdbc/template/testing/EmployeeDAO.java | 19 +++++++ .../template/guide}/application.properties | 0 .../spring/jdbc/template/guide}/schema.sql | 0 .../spring/jdbc/template/guide}/test-data.sql | 0 .../spring/jdbc/template/inclause/schema.sql | 7 +++ .../jdbc/template/inclause/test-data.sql | 7 +++ .../spring/jdbc/template/testing/schema.sql | 7 +++ .../jdbc/template/testing/test-data.sql | 7 +++ .../guide}/EmployeeDAOIntegrationTest.java | 6 +- .../inclause}/EmployeeDAOUnitTest.java | 45 +++------------ .../template/testing/EmployeeDAOUnitTest.java | 56 +++++++++++++++++++ .../spring-persistence-simple-2/README.md | 6 -- .../src/main/resources/jdbc/schema.sql | 6 -- .../src/main/resources/jdbc/test-data.sql | 4 -- .../spring-persistence-simple/.gitignore | 13 +++++ .../spring-persistence-simple/README.md | 25 +++++++++ .../pom.xml | 11 ++-- .../datasource/mock}/datasource.properties | 0 .../src/main/resources/jndi.properties | 2 +- .../datasource/mock}/SimpleJNDIUnitTest.java | 2 +- .../SimpleNamingContextBuilderManualTest.java | 2 +- 30 files changed, 224 insertions(+), 89 deletions(-) rename persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/{ => template/guide}/CustomSQLErrorCodeTranslator.java (93%) rename persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/{ => template/guide}/Employee.java (93%) rename persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/{ => template/guide}/EmployeeDAO.java (99%) rename persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/{ => template/guide}/EmployeeRowMapper.java (92%) rename persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/{ => template/guide}/config/SpringJdbcConfig.java (82%) create mode 100644 persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java rename persistence-modules/{spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc => spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause}/EmployeeDAO.java (88%) rename persistence-modules/{spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc => spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing}/Employee.java (93%) create mode 100644 persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java rename persistence-modules/spring-jdbc/src/main/resources/{ => com/baeldung/spring/jdbc/template/guide}/application.properties (100%) rename persistence-modules/spring-jdbc/src/main/resources/{jdbc => com/baeldung/spring/jdbc/template/guide}/schema.sql (100%) rename persistence-modules/spring-jdbc/src/main/resources/{jdbc => com/baeldung/spring/jdbc/template/guide}/test-data.sql (100%) create mode 100644 persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql create mode 100644 persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql create mode 100644 persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql create mode 100644 persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql rename persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/{ => template/guide}/EmployeeDAOIntegrationTest.java (94%) rename persistence-modules/{spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc => spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause}/EmployeeDAOUnitTest.java (69%) create mode 100644 persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java delete mode 100644 persistence-modules/spring-persistence-simple-2/README.md delete mode 100644 persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql delete mode 100644 persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql create mode 100644 persistence-modules/spring-persistence-simple/.gitignore create mode 100644 persistence-modules/spring-persistence-simple/README.md rename persistence-modules/{spring-persistence-simple-2 => spring-persistence-simple}/pom.xml (91%) rename persistence-modules/{spring-persistence-simple-2/src/main/resources/jndi => spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock}/datasource.properties (100%) rename persistence-modules/{spring-persistence-simple-2 => spring-persistence-simple}/src/main/resources/jndi.properties (69%) rename persistence-modules/{spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource => spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock}/SimpleJNDIUnitTest.java (95%) rename persistence-modules/{spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource => spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock}/SimpleNamingContextBuilderManualTest.java (96%) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 1a5ca8df70..4e46c9204b 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -86,7 +86,7 @@ spring-jpa-2 spring-jdbc - spring-persistence-simple-2 + spring-persistence-simple diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java similarity index 93% rename from persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java index aa0ffde00c..9beed9f9df 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/CustomSQLErrorCodeTranslator.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.SQLException; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java similarity index 93% rename from persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java index 84780e30da..32ca9ad0d3 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/Employee.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.guide; public class Employee { private int id; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java similarity index 99% rename from persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java index a6d0fe2f3b..11ecd84000 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java similarity index 92% rename from persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java index bf55d6160d..f4ea5ac7b6 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/EmployeeRowMapper.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java similarity index 82% rename from persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java index d7eb039637..0e81babd9a 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/config/SpringJdbcConfig.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc.config; +package com.baeldung.spring.jdbc.template.guide.config; import javax.sql.DataSource; @@ -17,8 +17,8 @@ public class SpringJdbcConfig { public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) - .addScript("classpath:jdbc/schema.sql") - .addScript("classpath:jdbc/test-data.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/guide/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/guide/test-data.sql") .build(); } diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java new file mode 100644 index 0000000000..c771033649 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.jdbc.template.inclause; + +public class Employee { + private int id; + + private String firstName; + + private String lastName; + + + public Employee(int id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java similarity index 88% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java index 6e2ad9682d..38b4a58355 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java @@ -1,10 +1,4 @@ -package com.baeldung.spring.jdbc; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.sql.DataSource; +package com.baeldung.spring.jdbc.template.inclause; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -12,6 +6,11 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Repository public class EmployeeDAO { private JdbcTemplate jdbcTemplate; @@ -22,15 +21,11 @@ public class EmployeeDAO { namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } - public int getCountOfEmployees() { - return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); - } - public List getEmployeesFromIdListNamed(List ids) { SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); List employees = namedJdbcTemplate.query( - "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", - parameters, + "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", + parameters, (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); return employees; @@ -39,8 +34,8 @@ public class EmployeeDAO { public List getEmployeesFromIdList(List ids) { String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); List employees = jdbcTemplate.query( - String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), - ids.toArray(), + String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), + ids.toArray(), (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); return employees; @@ -56,12 +51,11 @@ public class EmployeeDAO { jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds); List employees = jdbcTemplate.query( - "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", + "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); jdbcTemplate.update("DELETE FROM employee_tmp"); return employees; } - } diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java similarity index 93% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java index adc2255ca4..80be897827 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/spring/jdbc/Employee.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.testing; public class Employee { private int id; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java new file mode 100644 index 0000000000..64b146fd47 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.jdbc.template.testing; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; + +@Repository +public class EmployeeDAO { + private JdbcTemplate jdbcTemplate; + + public void setDataSource(DataSource dataSource) { + jdbcTemplate = new JdbcTemplate(dataSource); + } + + public int getCountOfEmployees() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/application.properties b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/application.properties similarity index 100% rename from persistence-modules/spring-jdbc/src/main/resources/application.properties rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/application.properties diff --git a/persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/schema.sql similarity index 100% rename from persistence-modules/spring-jdbc/src/main/resources/jdbc/schema.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/schema.sql diff --git a/persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/test-data.sql similarity index 100% rename from persistence-modules/spring-jdbc/src/main/resources/jdbc/test-data.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/test-data.sql diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql new file mode 100644 index 0000000000..ef4460e267 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255), + ADDRESS varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql new file mode 100644 index 0000000000..b9ef8fec25 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada'); + +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA'); + +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland'); + +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA'); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql new file mode 100644 index 0000000000..ef4460e267 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255), + ADDRESS varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql new file mode 100644 index 0000000000..b9ef8fec25 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada'); + +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA'); + +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland'); + +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA'); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java similarity index 94% rename from persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java index 10f47402be..c29d5c4534 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java @@ -1,9 +1,11 @@ -package com.baeldung.spring.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.util.ArrayList; import java.util.List; -import com.baeldung.spring.jdbc.config.SpringJdbcConfig; +import com.baeldung.spring.jdbc.template.guide.Employee; +import com.baeldung.spring.jdbc.template.guide.EmployeeDAO; +import com.baeldung.spring.jdbc.template.guide.config.SpringJdbcConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java similarity index 69% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java index bbc688293b..d9a858302b 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/spring/jdbc/EmployeeDAOUnitTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java @@ -1,22 +1,19 @@ -package com.baeldung.spring.jdbc; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; +package com.baeldung.spring.jdbc.template.inclause; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.util.ReflectionTestUtils; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; @RunWith(MockitoJUnitRunner.class) @@ -30,33 +27,9 @@ public class EmployeeDAOUnitTest { public void setup() { dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) .generateUniqueName(true) - .addScript("classpath:jdbc/schema.sql") - .addScript("classpath:jdbc/test-data.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/test-data.sql") .build(); - - } - - @Test - public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { - EmployeeDAO employeeDAO = new EmployeeDAO(); - ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); - Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) - .thenReturn(4); - - assertEquals(4, employeeDAO.getCountOfEmployees()); - - Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) - .thenReturn(3); - - assertEquals(3, employeeDAO.getCountOfEmployees()); - } - - @Test - public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { - EmployeeDAO employeeDAO = new EmployeeDAO(); - employeeDAO.setDataSource(dataSource); - - assertEquals(4, employeeDAO.getCountOfEmployees()); } @Test diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java new file mode 100644 index 0000000000..3609300c2d --- /dev/null +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.jdbc.template.testing; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.test.util.ReflectionTestUtils; + +import javax.sql.DataSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class EmployeeDAOUnitTest { + @Mock + JdbcTemplate jdbcTemplate; + + DataSource dataSource; + + @Before + public void setup() { + dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .generateUniqueName(true) + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/test-data.sql") + .build(); + } + + @Test + public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) + .thenReturn(4); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + + Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) + .thenReturn(3); + + assertEquals(3, employeeDAO.getCountOfEmployees()); + } + + @Test + public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + } +} diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md deleted file mode 100644 index d80c7efc57..0000000000 --- a/persistence-modules/spring-persistence-simple-2/README.md +++ /dev/null @@ -1,6 +0,0 @@ -### Relevant Articles: - -- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) -- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) -- [Transactional Annotations: Spring vs. JTA](https://www.baeldung.com/spring-vs-jta-transactional) -- [Test a Mock JNDI Datasource with Spring](https://www.baeldung.com/spring-mock-jndi-datasource) diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql deleted file mode 100644 index be102431ca..0000000000 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE EMPLOYEE -( - ID int NOT NULL PRIMARY KEY, - FIRST_NAME varchar(255), - LAST_NAME varchar(255) -); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql deleted file mode 100644 index 5421c09849..0000000000 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling'); -INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth'); -INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds'); -INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie'); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/.gitignore b/persistence-modules/spring-persistence-simple/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md new file mode 100644 index 0000000000..d665433eef --- /dev/null +++ b/persistence-modules/spring-persistence-simple/README.md @@ -0,0 +1,25 @@ +========= + +## Spring Persistence Example Project + + +### Relevant Articles: +- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) +- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) +- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) +- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) +- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/persistence-modules/spring-persistence-simple-2/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml similarity index 91% rename from persistence-modules/spring-persistence-simple-2/pom.xml rename to persistence-modules/spring-persistence-simple/pom.xml index b8f3b384a2..6ca0f3f025 100644 --- a/persistence-modules/spring-persistence-simple-2/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - spring-persistence-simple-2 + spring-persistence-simple 0.1-SNAPSHOT - spring-persistence-simple-2 + spring-persistence-simple com.baeldung @@ -32,7 +32,7 @@ ${h2.version} test - + com.github.h-thurow @@ -48,9 +48,9 @@ test - org.mockito + org.mockito mockito-core - ${mockito.version} + ${mockito.version} test @@ -65,5 +65,4 @@ 3.3.3
- \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jndi/datasource.properties b/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties similarity index 100% rename from persistence-modules/spring-persistence-simple-2/src/main/resources/jndi/datasource.properties rename to persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties b/persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties similarity index 69% rename from persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties rename to persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties index d976f16c02..4ab5b3ba8b 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties +++ b/persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties @@ -3,4 +3,4 @@ org.osjava.sj.jndi.shared=true org.osjava.sj.delimiter=. jndi.syntax.separator=/ org.osjava.sj.space=java:/comp/env -org.osjava.sj.root=src/main/resources/jndi +org.osjava.sj.root=src/main/resources/com/baeldung/spring/jndi/datasource/mock diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java similarity index 95% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java index 37f33b1192..6576962609 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jndi.datasource; +package com.baeldung.spring.jndi.datasource.mock; import static org.junit.Assert.assertEquals; diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java similarity index 96% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java index ac33be1c6f..f4c3e012f9 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jndi.datasource; +package com.baeldung.spring.jndi.datasource.mock; import static org.junit.Assert.assertNotNull; From 910bda6ef1215e1e8933ccbbe2de0a4b5bd1f1e5 Mon Sep 17 00:00:00 2001 From: fdpro Date: Mon, 31 Aug 2020 15:46:07 +0200 Subject: [PATCH 52/72] [JAVA-2306] Fixed READMEs * spring-jpa-2 * spring-data-jpa-repo-2 * spring-data-jpa-query-2 * spring-jdbc * spring-persistence-simple --- persistence-modules/spring-data-jpa-query-2/README.md | 1 + persistence-modules/spring-data-jpa-query/README.md | 1 - persistence-modules/spring-data-jpa-repo-2/README.md | 5 +++++ persistence-modules/spring-data-jpa-repo/README.md | 1 + persistence-modules/spring-jdbc/README.md | 6 ++++++ persistence-modules/spring-jpa-2/README.md | 5 +++++ persistence-modules/spring-persistence-simple/README.md | 9 +-------- 7 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-repo-2/README.md create mode 100644 persistence-modules/spring-jdbc/README.md diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index a4d657d4c6..1cb3d54da9 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -4,6 +4,7 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - More articles: [[<-- prev]](../spring-data-jpa-query) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-query/README.md b/persistence-modules/spring-data-jpa-query/README.md index 34e397394b..27443c2026 100644 --- a/persistence-modules/spring-data-jpa-query/README.md +++ b/persistence-modules/spring-data-jpa-query/README.md @@ -3,7 +3,6 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: -- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) - [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) - [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md new file mode 100644 index 0000000000..de5188c1ad --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -0,0 +1,5 @@ +## Spring Data JPA - Repositories + +### Relevant Articles: +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- More articles: [[<-- prev]](/spring-data-jpa-repo/) \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 284a7ac2b5..1a95340a97 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -11,6 +11,7 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- More articles: [[--> next]](/spring-data-jpa-repo-2/) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jdbc/README.md b/persistence-modules/spring-jdbc/README.md new file mode 100644 index 0000000000..58d7bdec43 --- /dev/null +++ b/persistence-modules/spring-jdbc/README.md @@ -0,0 +1,6 @@ +## Spring JDBC + +### Relevant Articles: +- [Spring JDBC Template](https://www.baeldung.com/spring-jdbc-jdbctemplate) +- [Spring JDBC Template Testing](https://www.baeldung.com/spring-jdbctemplate-testing) +- [Spring JDBC Template In Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/README.md b/persistence-modules/spring-jpa-2/README.md index b1786f49bd..fe661c2f28 100644 --- a/persistence-modules/spring-jpa-2/README.md +++ b/persistence-modules/spring-jpa-2/README.md @@ -2,4 +2,9 @@ ### Relevant Articles: - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) +- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) +- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) +- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - More articles: [[<-- prev]](/spring-jpa) \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index d665433eef..3239ec993b 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -4,15 +4,8 @@ ### Relevant Articles: -- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) -- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) -- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) -- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) - [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) +- [Mock JNDI Datasource](https://www.baeldung.com/spring-mock-jndi-datasource) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 3b41d6352dafe7dc2788fb32d37adb6df803f486 Mon Sep 17 00:00:00 2001 From: fdpro Date: Mon, 31 Aug 2020 16:29:31 +0200 Subject: [PATCH 53/72] [JAVA-2306] Moved last article to spring-jdbc --- .../spring/jdbc/autogenkey/config/PersistenceConfig.java | 2 +- .../autogenkey/repository/MessageRepositoryJDBCTemplate.java | 0 .../repository/MessageRepositorySimpleJDBCInsert.java | 0 .../com/baeldung/spring/jdbc/autogenkey}/autogenkey-schema.sql | 0 .../baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java | 2 +- 5 files changed, 2 insertions(+), 2 deletions(-) rename persistence-modules/{spring-jpa => spring-jdbc}/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java (90%) rename persistence-modules/{spring-jpa => spring-jdbc}/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java (100%) rename persistence-modules/{spring-jpa => spring-jdbc}/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java (100%) rename persistence-modules/{spring-jpa/src/main/resources => spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey}/autogenkey-schema.sql (100%) rename persistence-modules/{spring-jpa => spring-jdbc}/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java (93%) diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java index d1f8864357..6d36ac709f 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java @@ -16,7 +16,7 @@ public class PersistenceConfig { public DataSource dataSource(Environment env) { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) - .addScript("autogenkey-schema.sql") + .addScript("com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql") .build(); } diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java similarity index 100% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java similarity index 100% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java diff --git a/persistence-modules/spring-jpa/src/main/resources/autogenkey-schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql similarity index 100% rename from persistence-modules/spring-jpa/src/main/resources/autogenkey-schema.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java similarity index 93% rename from persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index f0ad853c2a..86a23ecc3e 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -7,6 +7,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; @@ -35,7 +36,6 @@ public class GetAutoGenKeyByJDBC { String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); assertEquals(MESSAGE_CONTENT, loadedMessage); - } @Test From 16f3fdd81b66fd5ccb1689b5c7d185dc2fe23b36 Mon Sep 17 00:00:00 2001 From: fdpro Date: Tue, 1 Sep 2020 20:05:04 +0200 Subject: [PATCH 54/72] [JAVA-2306] Added .sdkmanrc to .gitignore --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index fe56746dfd..88c5e49808 100644 --- a/.gitignore +++ b/.gitignore @@ -87,4 +87,7 @@ transaction.log apache-cxf/cxf-aegis/baeldung.xml testing-modules/report-*.json -libraries-2/*.db \ No newline at end of file +libraries-2/*.db + +# SDKMan +.sdkmanrc From 285890231d8a206eed1db8d0b9a16779f5f3654e Mon Sep 17 00:00:00 2001 From: fdpro Date: Tue, 1 Sep 2020 20:15:58 +0200 Subject: [PATCH 55/72] [JAVA-2306] Removed unnecessary Bar field in Foo class --- .../java/com/baeldung/spring/dao/generics/Foo.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java index 7849abb25f..33284d9b8e 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java @@ -30,18 +30,6 @@ public class Foo implements Serializable { @Column(name = "NAME") private String name; - @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar; - - public Bar getBar() { - return bar; - } - - public void setBar(final Bar bar) { - this.bar = bar; - } - public Long getId() { return id; } @@ -89,5 +77,4 @@ public class Foo implements Serializable { builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } - } From 3fd89261458d9f3dad82047428d2df583b2d0a8a Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Wed, 2 Sep 2020 23:56:02 +0200 Subject: [PATCH 56/72] BAEL-4297: fixed unsynchronized classes naming, added slf4j logging --- .../illegalmonitorstate/SynchronizedReceiver.java | 8 ++++++-- .../illegalmonitorstate/SynchronizedSender.java | 8 ++++++-- ...izedReceiver.java => UnsynchronizedReceiver.java} | 12 ++++++++---- ...hronizedSender.java => UnsynchronizedSender.java} | 12 ++++++++---- .../IllegalMonitorStateExceptionUnitTest.java | 4 ++-- 5 files changed, 30 insertions(+), 14 deletions(-) rename core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/{UnSynchronizedReceiver.java => UnsynchronizedReceiver.java} (66%) rename core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/{UnSynchronizedSender.java => UnsynchronizedSender.java} (64%) diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java index 3dffb7b30a..ff6b926cdc 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java @@ -1,6 +1,10 @@ package com.baeldung.exceptions.illegalmonitorstate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class SynchronizedReceiver implements Runnable { + private static Logger log = LoggerFactory.getLogger(SynchronizedReceiver.class); private final Data data; private String message; private boolean illegalMonitorStateExceptionOccurred; @@ -16,10 +20,10 @@ public class SynchronizedReceiver implements Runnable { data.wait(); this.message = data.receive(); } catch (InterruptedException e) { - e.printStackTrace(); + log.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { - e.printStackTrace(); + log.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java index 04bac03e77..1618bc8efa 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java @@ -1,6 +1,10 @@ package com.baeldung.exceptions.illegalmonitorstate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class SynchronizedSender implements Runnable { + private static Logger log = LoggerFactory.getLogger(SynchronizedSender.class); private final Data data; private boolean illegalMonitorStateExceptionOccurred; @@ -18,10 +22,10 @@ public class SynchronizedSender implements Runnable { data.notifyAll(); } catch (InterruptedException e) { - e.printStackTrace(); + log.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { - e.printStackTrace(); + log.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java similarity index 66% rename from core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java rename to core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java index a8e8befc4d..3a0b72e6cd 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedReceiver.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java @@ -1,11 +1,15 @@ package com.baeldung.exceptions.illegalmonitorstate; -public class UnSynchronizedReceiver implements Runnable { +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UnsynchronizedReceiver implements Runnable { + private static Logger log = LoggerFactory.getLogger(UnsynchronizedReceiver.class); private final Data data; private String message; private boolean illegalMonitorStateExceptionOccurred; - public UnSynchronizedReceiver(Data data) { + public UnsynchronizedReceiver(Data data) { this.data = data; } @@ -15,10 +19,10 @@ public class UnSynchronizedReceiver implements Runnable { data.wait(); this.message = data.receive(); } catch (InterruptedException e) { - e.printStackTrace(); + log.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { - e.printStackTrace(); + log.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java similarity index 64% rename from core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java rename to core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java index eb6fa16649..7f15418bfa 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnSynchronizedSender.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java @@ -1,10 +1,14 @@ package com.baeldung.exceptions.illegalmonitorstate; -public class UnSynchronizedSender implements Runnable { +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UnsynchronizedSender implements Runnable { + private static Logger log = LoggerFactory.getLogger(UnsynchronizedSender.class); private final Data data; private boolean illegalMonitorStateExceptionOccurred; - public UnSynchronizedSender(Data data) { + public UnsynchronizedSender(Data data) { this.data = data; } @@ -17,10 +21,10 @@ public class UnSynchronizedSender implements Runnable { data.notifyAll(); } catch (InterruptedException e) { - e.printStackTrace(); + log.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { - e.printStackTrace(); + log.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java index 800cdc4a7b..a729facdbd 100644 --- a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java @@ -30,7 +30,7 @@ public class IllegalMonitorStateExceptionUnitTest { void whenSyncSenderAndUnSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException { Data data = new Data(); - UnSynchronizedReceiver receiver = new UnSynchronizedReceiver(data); + UnsynchronizedReceiver receiver = new UnsynchronizedReceiver(data); Thread receiverThread = new Thread(receiver, "receiver-thread"); receiverThread.start(); @@ -55,7 +55,7 @@ public class IllegalMonitorStateExceptionUnitTest { Thread receiverThread = new Thread(receiver, "receiver-thread"); receiverThread.start(); - UnSynchronizedSender sender = new UnSynchronizedSender(data); + UnsynchronizedSender sender = new UnsynchronizedSender(data); Thread senderThread = new Thread(sender, "sender-thread"); senderThread.start(); From 5b20bb3d2a4608a4523827f2bfc85159bae454ef Mon Sep 17 00:00:00 2001 From: Marco Denisi Date: Thu, 3 Sep 2020 16:59:07 +0200 Subject: [PATCH 57/72] BAEL-3619 - add swagger samples --- .../openapi-3-date-format.yaml | 36 +++++++++++++++++++ .../openapi-3-date-pattern.yaml | 36 +++++++++++++++++++ .../openapi-3-datetime-format.yaml | 36 +++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml create mode 100644 spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml create mode 100644 spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml new file mode 100644 index 0000000000..7ee581d3d8 --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + createdAt: + type: string + format: date + description: Creation date + example: "2021-01-30" + username: + type: string \ No newline at end of file diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml new file mode 100644 index 0000000000..ffba36f3da --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + customDate: + type: string + pattern: '^\d{4}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$' + description: Custom date + example: "20210130" + username: + type: string \ No newline at end of file diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml new file mode 100644 index 0000000000..8bf4ddd2dc --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + createdAt: + type: string + format: date-time + description: Creation date and time + example: "2021-01-30T08:30:00Z" + username: + type: string \ No newline at end of file From 53360080dbb38bc7ee81f6fff8e573f766b6ec66 Mon Sep 17 00:00:00 2001 From: Sebastian Luna Date: Thu, 3 Sep 2020 20:49:20 -0500 Subject: [PATCH 58/72] BAEL-4387 Change Module --- .../baeldung/arrayconversion/ArrayToListConversionUnitTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {core-java-modules/core-java-string-operations-3 => java-collections-conversions-2}/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java (100%) diff --git a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java similarity index 100% rename from core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java rename to java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java From 68b732beb0103af02a3d5a40aa041a7bfb05a5f1 Mon Sep 17 00:00:00 2001 From: fdpro Date: Sat, 5 Sep 2020 14:59:15 +0200 Subject: [PATCH 59/72] [JAVA-2306] Fixes after Loredana's review * Brought back UserRepositoryCustomImpl.java * Added link to https://www.baeldung.com/spring-data-jpa-query in spring-data-jpa-query-2 README * Migrated code for https://www.baeldung.com/spring-data-jpa-query-by-date * Migrated https://www.baeldung.com/spring-vs-jta-transactional to spring-persistence-simple --- .../spring-data-jpa-query-2/README.md | 1 + .../jpa/query/UserRepositoryCustomImpl.java | 48 +++++++++++++++++++ .../data/jpa/query/datetime/Application.java} | 25 +++++----- .../data/jpa/query/datetime}/Article.java | 2 +- .../query/datetime}/ArticleRepository.java | 4 +- .../src/main/resources/import_entities.sql | 0 .../ArticleRepositoryIntegrationTest.java | 16 +++---- .../spring-persistence-simple/README.md | 1 + .../spring-persistence-simple/pom.xml | 29 +++++++++++ .../baeldung/spring/transactional}/Car.java | 2 +- .../spring/transactional}/CarRepository.java | 3 +- .../spring/transactional}/CarService.java | 4 +- .../spring/transactional}/RentalService.java | 4 +- 13 files changed, 105 insertions(+), 34 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java rename persistence-modules/{spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java} (55%) rename persistence-modules/{spring-data-jpa-query/src/main/java/com/baeldung/boot/domain => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime}/Article.java (88%) rename persistence-modules/{spring-data-jpa-query/src/main/java/com/baeldung/boot/daos => spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime}/ArticleRepository.java (90%) rename persistence-modules/{spring-data-jpa-query => spring-data-jpa-query-2}/src/main/resources/import_entities.sql (100%) rename persistence-modules/{spring-data-jpa-query/src/test/java/com/baeldung/boot/daos => spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime}/ArticleRepositoryIntegrationTest.java (96%) rename persistence-modules/{spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity => spring-persistence-simple/src/main/java/com/baeldung/spring/transactional}/Car.java (95%) rename persistence-modules/{spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository => spring-persistence-simple/src/main/java/com/baeldung/spring/transactional}/CarRepository.java (55%) rename persistence-modules/{spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service => spring-persistence-simple/src/main/java/com/baeldung/spring/transactional}/CarService.java (83%) rename persistence-modules/{spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service => spring-persistence-simple/src/main/java/com/baeldung/spring/transactional}/RentalService.java (75%) diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index 1cb3d54da9..fdb4ce3db7 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -3,6 +3,7 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: +- [Spring Data JPA @Query Annotation](https://www.baeldung.com/spring-data-jpa-query) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - More articles: [[<-- prev]](../spring-data-jpa-query) diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java new file mode 100644 index 0000000000..033f61fdd3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.data.jpa.query; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class UserRepositoryCustomImpl implements UserRepositoryCustom { + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findUserByEmails(Set emails) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(User.class); + Root user = query.from(User.class); + + Path emailPath = user.get("email"); + + List predicates = new ArrayList<>(); + for (String email : emails) { + + predicates.add(cb.like(emailPath, email)); + + } + query.select(user) + .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); + + return entityManager.createQuery(query) + .getResultList(); + } + + @Override + public List findAllUsersByPredicates(Collection> predicates) { + List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); + Stream allUsersStream = allUsers.stream(); + for (java.util.function.Predicate predicate : predicates) { + allUsersStream = allUsersStream.filter(predicate); + } + + return allUsersStream.collect(Collectors.toList()); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java similarity index 55% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java index 7fee55be8a..81e5a2f790 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java @@ -1,12 +1,13 @@ -package com.baeldung.spring.transactional; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -class TransactionalCompareApplication { - - public static void main(String[] args) { - SpringApplication.run(TransactionalCompareApplication.class, args); - } -} +package com.baeldung.spring.data.jpa.query.datetime; + +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/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java similarity index 88% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java index de4dbed1a0..bb0e4e88df 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.domain; +package com.baeldung.spring.data.jpa.query.datetime; import javax.persistence.*; import java.util.Date; diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java similarity index 90% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java index 73397ad42e..9ec14884f4 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java @@ -1,11 +1,9 @@ -package com.baeldung.boot.daos; +package com.baeldung.spring.data.jpa.query.datetime; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import com.baeldung.boot.domain.Article; - import java.util.Date; import java.util.List; diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa-query-2/src/main/resources/import_entities.sql similarity index 100% rename from persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql rename to persistence-modules/spring-data-jpa-query-2/src/main/resources/import_entities.sql diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java similarity index 96% rename from persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java index 20fc3cbeaf..38fd804195 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java @@ -1,11 +1,4 @@ -package com.baeldung.boot.daos; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; +package com.baeldung.spring.data.jpa.query.datetime; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,7 +6,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.boot.domain.Article; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index 3239ec993b..baa9107f4e 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -5,6 +5,7 @@ ### Relevant Articles: - [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) +- [JTA Transaction with Spring](https://www.baeldung.com/spring-vs-jta-transactional) - [Mock JNDI Datasource](https://www.baeldung.com/spring-mock-jndi-datasource) ### Eclipse Config diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 6ca0f3f025..a069f70994 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -26,6 +26,31 @@
+ + javax.persistence + javax.persistence-api + ${persistence-api.version} + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + javax.transaction + javax.transaction-api + ${transaction-api.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + com.h2database h2 @@ -58,7 +83,11 @@ 5.2.4.RELEASE + 2.3.3.RELEASE + 2.2 + 1.3 + 2.2.7.RELEASE 1.4.200 0.23.0 diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java similarity index 95% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java index 1219111ffa..cb0dc21f7d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.transactional.entity; +package com.baeldung.spring.transactional; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java similarity index 55% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java index f8ecc8f550..ca82954751 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.transactional.repository; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; import org.springframework.data.jpa.repository.JpaRepository; public interface CarRepository extends JpaRepository { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java similarity index 83% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java index 0821ddb02b..00396d191a 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java @@ -1,7 +1,5 @@ -package com.baeldung.spring.transactional.service; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; -import com.baeldung.spring.transactional.repository.CarRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java similarity index 75% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java index 0aa0815a98..468ac2e53d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java @@ -1,7 +1,5 @@ -package com.baeldung.spring.transactional.service; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; -import com.baeldung.spring.transactional.repository.CarRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; From 777aa4b4ea5da91cb0ca78132bbe33c7adc1c2b8 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 6 Sep 2020 00:31:09 +0530 Subject: [PATCH 60/72] updated spring-data-mongo and used compatible mongo version --- persistence-modules/spring-data-mongodb/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 46dbc270c3..ec7aa14c36 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -121,7 +121,7 @@ 4.1.0 3.2.0.RELEASE Lovelace-SR9 - 4.1.0 + 4.0.5 From be8c51e3e0b585afbb72cb365045722bc8a5cb35 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 6 Sep 2020 20:05:15 +0530 Subject: [PATCH 61/72] removed unwanted dependency from pom --- persistence-modules/spring-data-mongodb/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index ec7aa14c36..fdcaf1d49b 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -19,12 +19,6 @@ ${org.springframework.data.version} - - org.mongodb - mongodb-driver-core - ${mongodb-driver.version} - - org.mongodb mongodb-driver-sync From 1927bb1b460752245b26b441a637138e0eebaaa2 Mon Sep 17 00:00:00 2001 From: developerDiv <34768329+developerDiv@users.noreply.github.com> Date: Sun, 6 Sep 2020 16:27:59 +0100 Subject: [PATCH 62/72] BAEL-4287 - Rolling Back Migrations with Flyway (#9910) * First commit - Flyway Undo * Simplify migrations Move to own package --- .../db/undo/V1_0__create_book_table.sql | 6 +++ .../db/undo/V2_0__drop_table_book.sql | 1 + .../FlywayUndoMigrationIntegrationTest.java | 39 +++++++++++++++++++ .../flywayundo/FlywayUndoTestConfig.java | 21 ++++++++++ 4 files changed, 67 insertions(+) create mode 100644 persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql create mode 100644 persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql create mode 100644 persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java create mode 100644 persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java diff --git a/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql b/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql new file mode 100644 index 0000000000..105da7a0c0 --- /dev/null +++ b/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql @@ -0,0 +1,6 @@ +create table book ( + id numeric, + title varchar(128), + author varchar(256), + constraint pk_book primary key (id) +); \ No newline at end of file diff --git a/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql b/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql new file mode 100644 index 0000000000..cd800b00b7 --- /dev/null +++ b/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql @@ -0,0 +1 @@ +drop table book; \ No newline at end of file diff --git a/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java new file mode 100644 index 0000000000..03004baf60 --- /dev/null +++ b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.flywayundo; + +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationState; +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = FlywayUndoTestConfig.class) +@SpringBootTest +public class FlywayUndoMigrationIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenMigrationsExist_whenApplyMigrations_migrationsAreSuccessful() { + Flyway flyway = Flyway.configure() + .dataSource(dataSource) + .schemas("undo") + .locations("db/undo") + .load(); + + flyway.migrate(); + + for (MigrationInfo info : flyway.info().all()) { + assertThat(info.getState()).isEqualTo(MigrationState.SUCCESS); + } + } +} diff --git a/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java new file mode 100644 index 0000000000..5f00626179 --- /dev/null +++ b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.flywayundo; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +import javax.sql.DataSource; + +@Configuration +public class FlywayUndoTestConfig { + + @Bean + public DataSource createDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("DATABASE") + .build(); + } + +} From 74efd2530ef142902a10b44431d6981d789f577c Mon Sep 17 00:00:00 2001 From: fanatixan Date: Mon, 7 Sep 2020 04:13:25 +0200 Subject: [PATCH 63/72] added code snippets for bael-4554 (#9979) --- .../mockito/whenvsdomethods/Employee.java | 11 +++ .../IAmOnHolidayException.java | 5 ++ .../WhenVsDoMethodsUnitTest.java | 90 +++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java new file mode 100644 index 0000000000..4bbd2843f2 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java @@ -0,0 +1,11 @@ +package com.baeldung.mockito.whenvsdomethods; + +import java.time.DayOfWeek; + +public interface Employee { + + String greet(); + + void work(DayOfWeek day); + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java new file mode 100644 index 0000000000..24276ba958 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java @@ -0,0 +1,5 @@ +package com.baeldung.mockito.whenvsdomethods; + +public class IAmOnHolidayException extends RuntimeException { + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java new file mode 100644 index 0000000000..8c2b86daf1 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.mockito.whenvsdomethods; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import java.time.DayOfWeek; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class WhenVsDoMethodsUnitTest { + + @Mock + private Employee employee; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + void givenNonVoidMethod_callingWhen_shouldConfigureBehavior() { + // given + when(employee.greet()).thenReturn("Hello"); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenNonVoidMethod_callingDoReturn_shouldConfigureBehavior() { + // given + doReturn("Hello").when(employee).greet(); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenVoidMethod_callingDoThrow_shouldConfigureBehavior() { + // given + doThrow(new IAmOnHolidayException()).when(employee).work(DayOfWeek.SUNDAY); + + // when + Executable workCall = () -> employee.work(DayOfWeek.SUNDAY); + + // then + assertThrows(IAmOnHolidayException.class, workCall); + } + + @Test + void givenNonVoidMethod_callingGiven_shouldConfigureBehavior() { + // given + given(employee.greet()).willReturn("Hello"); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenVoidMethod_callingWillThrow_shouldConfigureBehavior() { + // given + willThrow(new IAmOnHolidayException()).given(employee).work(DayOfWeek.SUNDAY); + + // when + Executable workCall = () -> employee.work(DayOfWeek.SUNDAY); + + // then + assertThrows(IAmOnHolidayException.class, workCall); + } + +} From 8278cc272a86dd4d9f8eb438d809c8aac3e17f30 Mon Sep 17 00:00:00 2001 From: majajoksovic Date: Mon, 7 Sep 2020 04:19:12 +0200 Subject: [PATCH 64/72] added braces (#9972) --- .../src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java | 2 +- .../src/main/java/com/baeldung/ssh/jsch/JschDemo.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) 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 index 05d8034040..8a394640c7 100644 --- a/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java +++ b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java @@ -32,7 +32,7 @@ public class SshdDemo { .getSession()) { session.addPasswordIdentity(password); session.auth() - .verify(5L, TimeUnit.SECONDS); + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) { 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 index 34a40318bb..8a6567bfee 100644 --- a/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java +++ b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java @@ -42,10 +42,12 @@ public class JschDemo { throw new Exception(errorResponse); } } finally { - if (session != null) + if (session != null) { session.disconnect(); - if (channel != null) + } + if (channel != null) { channel.disconnect(); + } } return response; } From f5b4367c1cc0e9802806e966e488a37552a0bf11 Mon Sep 17 00:00:00 2001 From: Loredana Date: Mon, 7 Sep 2020 14:53:22 +0300 Subject: [PATCH 65/72] formatting, remove unneeded dependency --- persistence-modules/spring-data-mongodb/pom.xml | 9 --------- .../src/main/java/com/baeldung/config/MongoConfig.java | 2 +- .../baeldung/transaction/MongoTransactionalLiveTest.java | 2 -- 3 files changed, 1 insertion(+), 12 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index fdcaf1d49b..60e59f5186 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -24,14 +24,6 @@ mongodb-driver-sync ${mongodb-driver.version} - - - - org.springframework.data - spring-data-releasetrain - ${spring-releasetrain} - pom - org.mongodb @@ -114,7 +106,6 @@ 1.1.3 4.1.0 3.2.0.RELEASE - Lovelace-SR9 4.0.5 diff --git a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 6851b5df6e..8036bbbca2 100644 --- a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -81,7 +81,7 @@ public class MongoConfig extends AbstractMongoClientConfiguration { @Bean MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { - return new MongoTransactionManager(dbFactory); + return new MongoTransactionManager(dbFactory); } } diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index 6cd9657006..d92296beab 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -2,7 +2,6 @@ package com.baeldung.transaction; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import java.util.List; @@ -22,7 +21,6 @@ import org.springframework.transaction.annotation.Transactional; import com.baeldung.config.MongoConfig; import com.baeldung.model.User; import com.baeldung.repository.UserRepository; -import com.mongodb.MongoCommandException; /** * From 9c5ed84bd40e660a3a9be21a6f2352f68f49ad31 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Mon, 7 Sep 2020 21:15:50 +0530 Subject: [PATCH 66/72] JAVA-2422: Merge spring-groovy into spring-boot-groovy (#9970) * JAVA-2422: Moved article to spring-boot-groovy * JAVA-2422: removed module spring-groovy * JAVA-2422: Moved spring-boot-groovy inside spring-boot-modules module * JAVA-2422: Added entry to spring-boot-module's pom * JAVA-2422: main pom changes for module movements * JAVA-2422: Renamed test as it needs the app up and running * JAVA-2422: Renamed test to live as it needs App to be running --- pom.xml | 8 +-- spring-boot-groovy/README.md | 3 - spring-boot-modules/pom.xml | 1 + .../spring-boot-groovy/README.md | 9 +++ .../spring-boot-groovy}/pom.xml | 4 +- .../SpringBootGroovyApplication.groovy | 0 .../controller/TodoController.groovy | 0 .../springwithgroovy/entity/Todo.groovy | 0 .../repository/TodoRepository.groovy | 0 .../service/TodoService.groovy | 0 .../service/impl/TodoServiceImpl.groovy | 0 .../com/baeldung}/groovyconfig/BandsBean.java | 2 +- .../groovyconfig/GroovyBeanConfig.groovy | 2 +- .../groovyconfig/JavaBeanConfig.java | 2 +- .../groovyconfig/JavaPersonBean.java | 2 +- .../java/com/baeldung}/spring_groovy/App.java | 2 +- .../baeldung}/spring_groovy/TestConfig.java | 2 +- .../src/main/resources/application.properties | 0 .../main/resources/groovyContextConfig.groovy | 0 .../src/main/resources/logback.xml | 0 .../src/main/resources/xml-bean-config.xml | 2 +- .../springwithgroovy/TodoAppLiveTest.groovy | 7 +- .../GroovyConfigurationUnitTest.java | 7 +- .../JavaConfigurationUnitTest.java | 5 +- .../XmlConfigurationUnitTest.java | 4 +- .../baeldung}/spring_groovy/AppUnitTest.java | 2 +- spring-groovy/.gitignore | 7 -- spring-groovy/README.md | 7 -- spring-groovy/pom.xml | 67 ------------------- 29 files changed, 39 insertions(+), 106 deletions(-) delete mode 100644 spring-boot-groovy/README.md create mode 100644 spring-boot-modules/spring-boot-groovy/README.md rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/pom.xml (94%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy (100%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy (100%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy (100%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy (100%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy (100%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy (100%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/groovyconfig/BandsBean.java (89%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/groovyconfig/GroovyBeanConfig.groovy (90%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/groovyconfig/JavaBeanConfig.java (93%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/groovyconfig/JavaPersonBean.java (96%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/spring_groovy/App.java (80%) rename {spring-groovy/src/main/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung}/spring_groovy/TestConfig.java (71%) rename {spring-boot-groovy => spring-boot-modules/spring-boot-groovy}/src/main/resources/application.properties (100%) rename {spring-groovy => spring-boot-modules/spring-boot-groovy}/src/main/resources/groovyContextConfig.groovy (100%) rename {spring-groovy => spring-boot-modules/spring-boot-groovy}/src/main/resources/logback.xml (100%) rename {spring-groovy => spring-boot-modules/spring-boot-groovy}/src/main/resources/xml-bean-config.xml (87%) rename spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy => spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy (93%) rename {spring-groovy/src/test/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung}/groovyconfig/GroovyConfigurationUnitTest.java (90%) rename {spring-groovy/src/test/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung}/groovyconfig/JavaConfigurationUnitTest.java (82%) rename {spring-groovy/src/test/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung}/groovyconfig/XmlConfigurationUnitTest.java (88%) rename {spring-groovy/src/test/java/com/baeldug => spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung}/spring_groovy/AppUnitTest.java (94%) delete mode 100644 spring-groovy/.gitignore delete mode 100644 spring-groovy/README.md delete mode 100644 spring-groovy/pom.xml diff --git a/pom.xml b/pom.xml index ffdfe4cffa..a2e09c0f91 100644 --- a/pom.xml +++ b/pom.xml @@ -655,9 +655,7 @@ spring-ejb spring-exceptions - spring-freemarker - - spring-groovy + spring-freemarker spring-integration @@ -1159,9 +1157,7 @@ spring-ejb spring-exceptions - spring-freemarker - - spring-groovy + spring-freemarker spring-integration diff --git a/spring-boot-groovy/README.md b/spring-boot-groovy/README.md deleted file mode 100644 index d2472a11d0..0000000000 --- a/spring-boot-groovy/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 109be01db3..527f7dcad8 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -41,6 +41,7 @@ spring-boot-environment spring-boot-exceptions spring-boot-flowable + spring-boot-groovy spring-boot-jasypt spring-boot-keycloak diff --git a/spring-boot-modules/spring-boot-groovy/README.md b/spring-boot-modules/spring-boot-groovy/README.md new file mode 100644 index 0000000000..73edafb9c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-groovy/README.md @@ -0,0 +1,9 @@ +## Spring Boot Groovy + +This module contains articles about Spring with Groovy + + +### Relevant Articles: + +- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app) +- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) \ No newline at end of file diff --git a/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml similarity index 94% rename from spring-boot-groovy/pom.xml rename to spring-boot-modules/spring-boot-groovy/pom.xml index 9ea8d7b2a9..3392532081 100644 --- a/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -14,7 +14,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 @@ -72,7 +72,7 @@ - com.baeldung.app.SpringBootGroovyApplication + com.baeldung.springwithgroovy.SpringBootGroovyApplication diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java similarity index 89% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java index 1deba5d2f6..29f143c66c 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import java.util.ArrayList; import java.util.List; diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy similarity index 90% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy index 32a6fedff0..3237226877 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; beans { javaPesronBean(JavaPersonBean) { diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java similarity index 93% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java index 7c4238ae28..64926f606b 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java similarity index 96% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java index db988d4abf..da0b92451e 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; public class JavaPersonBean { diff --git a/spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java similarity index 80% rename from spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java index 1df6681c42..2465683c5f 100644 --- a/spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; /** * Hello world! diff --git a/spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java similarity index 71% rename from spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java index 474216de4e..04ff38c475 100644 --- a/spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; import org.springframework.stereotype.Component; diff --git a/spring-boot-groovy/src/main/resources/application.properties b/spring-boot-modules/spring-boot-groovy/src/main/resources/application.properties similarity index 100% rename from spring-boot-groovy/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-groovy/src/main/resources/application.properties diff --git a/spring-groovy/src/main/resources/groovyContextConfig.groovy b/spring-boot-modules/spring-boot-groovy/src/main/resources/groovyContextConfig.groovy similarity index 100% rename from spring-groovy/src/main/resources/groovyContextConfig.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/resources/groovyContextConfig.groovy diff --git a/spring-groovy/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-groovy/src/main/resources/logback.xml similarity index 100% rename from spring-groovy/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-groovy/src/main/resources/logback.xml diff --git a/spring-groovy/src/main/resources/xml-bean-config.xml b/spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml similarity index 87% rename from spring-groovy/src/main/resources/xml-bean-config.xml rename to spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml index 3b880bbd70..b26f28f7b1 100644 --- a/spring-groovy/src/main/resources/xml-bean-config.xml +++ b/spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy b/spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy similarity index 93% rename from spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy rename to spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy index bf8b0ff27f..6ae6ffcd73 100644 --- a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy @@ -17,8 +17,11 @@ import com.baeldung.springwithgroovy.entity.Todo import io.restassured.RestAssured import io.restassured.response.Response -class TodoAppUnitTest { - static API_ROOT = 'http://localhost:8081/todo' +// This test requires the com.baeldung.springwithgroovy.SpringBootGroovyApplication to be up +// For that, run the maven build - spring-boot:run on the module + +class TodoAppLiveTest { + static API_ROOT = 'http://localhost:8080/todo' static readingTodoId static writingTodoId diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java similarity index 90% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java index dbefba5ba5..bd46ded977 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.assertEquals; @@ -7,10 +7,13 @@ import java.io.File; import org.junit.Test; import org.springframework.context.support.GenericGroovyApplicationContext; +import com.baeldung.groovyconfig.BandsBean; +import com.baeldung.groovyconfig.JavaPersonBean; + public class GroovyConfigurationUnitTest { private static final String FILE_NAME = "GroovyBeanConfig.groovy"; - private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; + private static final String FILE_PATH = "src/main/java/com/baeldung/groovyconfig/"; @Test public void whenGroovyConfig_thenCorrectPerson() throws Exception { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java similarity index 82% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java index c1e16f1b62..2ab1998853 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java @@ -1,10 +1,13 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import com.baeldung.groovyconfig.JavaBeanConfig; +import com.baeldung.groovyconfig.JavaPersonBean; + public class JavaConfigurationUnitTest { @Test diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java similarity index 88% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java index b8d341ee39..aa9f3bd8f7 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.*; @@ -6,6 +6,8 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import com.baeldung.groovyconfig.JavaPersonBean; + public class XmlConfigurationUnitTest { @Test diff --git a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java similarity index 94% rename from spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java index 3d8fa3e2d8..9702e98ab8 100644 --- a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; import junit.framework.Test; import junit.framework.TestCase; diff --git a/spring-groovy/.gitignore b/spring-groovy/.gitignore deleted file mode 100644 index c17c227305..0000000000 --- a/spring-groovy/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -/target/ -/project/ -.classpath -.settings -.eclipse -.idea -.project diff --git a/spring-groovy/README.md b/spring-groovy/README.md deleted file mode 100644 index c3bb5636ba..0000000000 --- a/spring-groovy/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Spring Groovy - -This module contains articles about Spring with Groovy - -## Relevant Articles: - -- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml deleted file mode 100644 index ef5613adf6..0000000000 --- a/spring-groovy/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.baeldug - spring-groovy - 0.0.1-SNAPSHOT - spring-groovy - jar - http://maven.apache.org - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - org.springframework.integration - spring-integration-groovy - ${spring-integration-groovy.version} - - - org.codehaus.groovy - groovy-all - ${groovy-all.version} - - - - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - groovy-eclipse-compiler - true - ${java.version} - ${java.version} - ${project.build.sourceEncoding} - - - - org.codehaus.groovy - groovy-eclipse-compiler - ${groovy-eclipse-compiler.version} - - - org.codehaus.groovy - groovy-eclipse-batch - ${groovy-eclipse-batch.version} - - - - - - - - 2.9.2-01 - 2.4.3-01 - 4.3.7.RELEASE - 2.4.12 - - - From 30e4e277e0c6de6c1b43a507787e20fe4858924b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Mon, 7 Sep 2020 18:02:25 +0200 Subject: [PATCH 67/72] [JAVA-2427] Migrated spring-drools to parent-spring-5 (#9964) * [JAVA-2427] Migrated spring-drools to parent-spring-5 * [JAVA-2427] Added spring dependencies so that they all have the last version --- spring-drools/pom.xml | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml index 5adef4b2a9..8b105158ec 100644 --- a/spring-drools/pom.xml +++ b/spring-drools/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 @@ -40,17 +41,40 @@ kie-spring ${drools-version} + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + org.springframework spring-test - ${spring-framework.version} + ${spring.version} test 7.0.0.Final - 4.3.3.RELEASE - \ No newline at end of file From 98bdb5df3650304912a8731e925a5a4c91bf148c Mon Sep 17 00:00:00 2001 From: fdpro Date: Tue, 8 Sep 2020 11:53:26 +0200 Subject: [PATCH 68/72] [JAVA-2429] Migrated spring-data-solr module to parent-boot-5 --- persistence-modules/spring-data-solr/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index 9d96c75082..5386c4f9e1 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 From 760d54eb438820d73cfe99d7db03a4c9a346717b Mon Sep 17 00:00:00 2001 From: fdpro Date: Tue, 8 Sep 2020 11:48:05 +0200 Subject: [PATCH 69/72] [JAVA-2430] Migrated spring-data-cassandra to parent-boot-5 --- .../spring-data-cassandra/pom.xml | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 0f0aae4ebf..b44324dc46 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 @@ -30,6 +30,31 @@ + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + org.springframework spring-test From 0748a7534ff97866d1418f45eb0783db476439d7 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Tue, 8 Sep 2020 21:09:16 +0430 Subject: [PATCH 70/72] Non-Local Returns (#9934) --- .../main/kotlin/com/baeldung/inline/Inline.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt index 3b179642ba..aaa6616ed1 100644 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt @@ -22,6 +22,30 @@ fun main() { numbers.each { println(random * it) } // capturing the random variable } +fun namedFunction(): Int { + return 42 +} + +fun anonymous(): () -> Int { + return fun(): Int { + return 42 + } +} + +inline fun List.eachIndexed(f: (Int, T) -> Unit) { + for (i in indices) { + f(i, this[i]) + } +} + +fun List.indexOf(x: T): Int { + eachIndexed { index, value -> + if (value == x) return index + } + + return -1 +} + /** * Generates a random number. */ From 1876f16449519f8240b1519a0f62e555a78b9e25 Mon Sep 17 00:00:00 2001 From: fdpro Date: Wed, 9 Sep 2020 10:02:27 +0200 Subject: [PATCH 71/72] [JAVA-2433] Inherited from parent-spring-5 --- .../spring-security-web-digest-auth/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/spring-security-web-digest-auth/pom.xml b/spring-security-modules/spring-security-web-digest-auth/pom.xml index 2579a11f97..39433c1295 100644 --- a/spring-security-modules/spring-security-web-digest-auth/pom.xml +++ b/spring-security-modules/spring-security-web-digest-auth/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 From 99381e0b1528cfe703b30de3d38eea7aaa839df5 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Wed, 9 Sep 2020 18:35:31 +0200 Subject: [PATCH 72/72] BAEL-4588: Update Guide To Java 8 Optional (#9995) * BAEL-4588: Fix maven-shade-plugin version * BAEL-4588: Add empty core-java-11-2 module structure * BAEL-4588: Move Guide To Java 8 Optional to core-java-11-2 * BAEL-4588: Add Java 10 orElseThrow() example --- core-java-modules/core-java-11-2/README.md | 7 +++ core-java-modules/core-java-11-2/pom.xml | 48 +++++++++++++++++++ .../java/com/baeldung/optional/Modem.java | 0 .../java/com/baeldung/optional/Person.java | 0 .../optional/OptionalChainingUnitTest.java | 4 +- .../baeldung/optional/OptionalUnitTest.java | 10 +++- core-java-modules/core-java-11/pom.xml | 2 +- .../core-java-optional/README.md | 1 - 8 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 core-java-modules/core-java-11-2/README.md create mode 100644 core-java-modules/core-java-11-2/pom.xml rename core-java-modules/{core-java-optional => core-java-11-2}/src/main/java/com/baeldung/optional/Modem.java (100%) rename core-java-modules/{core-java-optional => core-java-11-2}/src/main/java/com/baeldung/optional/Person.java (100%) rename core-java-modules/{core-java-optional => core-java-11-2}/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java (96%) rename core-java-modules/{core-java-optional => core-java-11-2}/src/test/java/com/baeldung/optional/OptionalUnitTest.java (96%) diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md new file mode 100644 index 0000000000..f65a043819 --- /dev/null +++ b/core-java-modules/core-java-11-2/README.md @@ -0,0 +1,7 @@ +## Core Java 11 + +This module contains articles about Java 11 core features + +### Relevant articles +- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional) + diff --git a/core-java-modules/core-java-11-2/pom.xml b/core-java-modules/core-java-11-2/pom.xml new file mode 100644 index 0000000000..d20b0f23f0 --- /dev/null +++ b/core-java-modules/core-java-11-2/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + core-java-11-2 + 0.1.0-SNAPSHOT + core-java-11-2 + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + + + + 11 + 11 + 3.17.2 + + + diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Modem.java b/core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Modem.java similarity index 100% rename from core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Modem.java rename to core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Modem.java diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Person.java similarity index 100% rename from core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java rename to core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Person.java diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java similarity index 96% rename from core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java index 9ef156501b..65b9e22f44 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java @@ -7,7 +7,9 @@ import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Stream; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class OptionalChainingUnitTest { diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java similarity index 96% rename from core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java index de16e9b635..1b0a2d4445 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -9,7 +9,9 @@ import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class OptionalUnitTest { @@ -262,6 +264,12 @@ public class OptionalUnitTest { .orElseThrow(IllegalArgumentException::new); } + @Test(expected = NoSuchElementException.class) + public void whenNoArgOrElseThrowWorks_thenCorrect() { + String nullName = null; + String name = Optional.ofNullable(nullName).orElseThrow(); + } + public String getMyDefault() { LOG.debug("Getting default value..."); return "Default Value"; diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index bbc4219eaa..2f7f5a6bcf 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -107,7 +107,7 @@ benchmarks 1.22 10.0.0 - 10.0.0 + 3.2.4 diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md index d9d2fe813b..6c83003ea2 100644 --- a/core-java-modules/core-java-optional/README.md +++ b/core-java-modules/core-java-optional/README.md @@ -4,7 +4,6 @@ This module contains articles about Java Optional. ### Relevant Articles: - [Java Optional as Return Type](https://www.baeldung.com/java-optional-return) -- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional) - [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional) - [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)