diff --git a/.gitignore b/.gitignore index 50cb889e5b..2edea19340 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ */bin/* +bin/ *.class @@ -21,6 +22,9 @@ *.iws out/ +# VSCode +.vscode/ + # Mac .DS_Store @@ -77,4 +81,5 @@ apache-avro/src/main/java/com/baeldung/avro/model/ jta/transaction-logs/ software-security/sql-injection-samples/derby.log spring-soap/src/main/java/com/baeldung/springsoap/gen/ -/report-*.json \ No newline at end of file +/report-*.json +transaction.log \ No newline at end of file diff --git a/README.md b/README.md index 1030cbb09c..7f78cf1515 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -#Running Tests +###Running Tests The command `mvn clean install` will run the unit tests in a module. To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index 30130208f8..affa66f147 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -83,6 +83,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 7a83a97c5b..cd3711d573 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -5,3 +5,5 @@ - [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) +- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) +- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java new file mode 100644 index 0000000000..c130e2d866 --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.shellsort; + +public class ShellSort { + + public static void sort(int arrayToSort[]) { + int n = arrayToSort.length; + + for (int gap = n / 2; gap > 0; gap /= 2) { + for (int i = gap; i < n; i++) { + int key = arrayToSort[i]; + int j = i; + while (j >= gap && arrayToSort[j - gap] > key) { + arrayToSort[j] = arrayToSort[j - gap]; + j -= gap; + } + arrayToSort[j] = key; + } + } + } +} diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java new file mode 100644 index 0000000000..91a27c41d0 --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.shellsort; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class ShellSortUnitTest { + + @Test + public void givenUnsortedArray_whenShellSort_thenSortedAsc() { + int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8}; + ShellSort.sort(input); + int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82}; + assertArrayEquals("the two arrays are not equal", expected, input); + } +} diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 5d170f0a81..e6fb4d24ff 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -17,7 +17,7 @@ junit junit - 4.10 + ${junit.version} test diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 1efd4ea602..24e7b4e0b2 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -3,37 +3,28 @@ 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 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - org.baeldung.examples.olingo2 olingo2-sample 0.0.1-SNAPSHOT olingo2-sample Sample Olingo 2 Project - - 1.8 - 2.0.11 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + - org.springframework.boot spring-boot-starter-jersey - - org.springframework.boot spring-boot-starter-data-jpa - - com.h2database h2 @@ -90,4 +81,8 @@ + + 2.0.11 + + diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java similarity index 86% rename from apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java rename to apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java index 687f6ab1ff..7cb685e3e9 100644 --- a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java +++ b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class Olingo2SampleApplicationTests { +public class Olingo2SampleApplicationUnitTest { @Test public void contextLoads() { diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index 11df6d0b87..8a0882dae1 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -7,6 +7,13 @@ 0.0.1 apache-pulsar + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + org.apache.pulsar diff --git a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java index 72dc10b542..82a0028837 --- a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java @@ -7,7 +7,7 @@ import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.SubscriptionType; -public class ConsumerTest { +public class ConsumerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ProducerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java index 08ee0e89b9..10a4b46c4d --- a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.PulsarClientException; import java.io.IOException; import java.util.stream.IntStream; -public class ProducerTest { +public class ProducerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java index efb898eaf4..79121347e7 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java @@ -10,7 +10,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class ExclusiveSubscriptionTest { +public class ExclusiveSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java index 545661e0c3..1d13b4b83a 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class FailoverSubscriptionTest { +public class FailoverSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "failover-subscription-test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index f0f002a7e9..b8c1962dd4 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -49,6 +49,7 @@ ${com.datastax.spark.spark-cassandra-connector-java.version} + @@ -78,6 +79,7 @@ + 2.3.0 2.3.0 diff --git a/autovalue/README.md b/autovalue/README.md index c6a08359ef..f33ff6899f 100644 --- a/autovalue/README.md +++ b/autovalue/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) - [Introduction to AutoFactory](http://www.baeldung.com/autofactory) +- [Google AutoService](https://www.baeldung.com/google-autoservice) diff --git a/aws/pom.xml b/aws/pom.xml index 560f9145f9..75d5aac1eb 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -112,7 +112,6 @@ - 2.5 1.3.0 1.1.0 2.8.0 diff --git a/axon/pom.xml b/axon/pom.xml index 2b9ac1fcdd..3d30cceb83 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -18,12 +18,6 @@ org.axonframework axon-spring-boot-starter ${axon.version} - - - org.axonframework - axon-server-connector - - @@ -58,7 +52,7 @@ - 4.0.3 + 4.1.2 \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java index b37b2fdd66..4ef02e6b54 100644 --- a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java +++ b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java @@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand; import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; import com.baeldung.axon.coreapi.events.OrderPlacedEvent; import com.baeldung.axon.coreapi.events.OrderShippedEvent; +import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException; @Aggregate public class OrderAggregate { @@ -34,7 +35,7 @@ public class OrderAggregate { @CommandHandler public void handle(ShipOrderCommand command) { if (!orderConfirmed) { - throw new IllegalStateException("Cannot ship an order which has not been confirmed yet."); + throw new UnconfirmedOrderException(); } apply(new OrderShippedEvent(orderId)); @@ -43,12 +44,12 @@ public class OrderAggregate { @EventSourcingHandler public void on(OrderPlacedEvent event) { this.orderId = event.getOrderId(); - orderConfirmed = false; + this.orderConfirmed = false; } @EventSourcingHandler public void on(OrderConfirmedEvent event) { - orderConfirmed = true; + this.orderConfirmed = true; } protected OrderAggregate() { diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java new file mode 100644 index 0000000000..1873bc6893 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java @@ -0,0 +1,8 @@ +package com.baeldung.axon.coreapi.exceptions; + +public class UnconfirmedOrderException extends IllegalStateException { + + public UnconfirmedOrderException() { + super("Cannot ship an order which has not been confirmed yet."); + } +} diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java index d4cf3d999b..a37f0111ed 100644 --- a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java +++ b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.axonframework.config.ProcessingGroup; import org.axonframework.eventhandling.EventHandler; import org.axonframework.queryhandling.QueryHandler; import org.springframework.stereotype.Service; @@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery; import com.baeldung.axon.coreapi.queries.OrderedProduct; @Service +@ProcessingGroup("ordered-products") public class OrderedProductsEventHandler { private final Map orderedProducts = new HashMap<>(); diff --git a/axon/src/main/resources/application.properties b/axon/src/main/resources/application.properties new file mode 100644 index 0000000000..7c51eb8e1e --- /dev/null +++ b/axon/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=Order Management Service \ No newline at end of file diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java index 9beedbaa19..aaefe49fb1 100644 --- a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java +++ b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java @@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel; import java.util.UUID; +import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException; import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.FixtureConfiguration; import org.junit.*; @@ -41,12 +42,12 @@ public class OrderAggregateUnitTest { } @Test - public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() { + public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() { String orderId = UUID.randomUUID().toString(); String product = "Deluxe Chair"; fixture.given(new OrderPlacedEvent(orderId, product)) .when(new ShipOrderCommand(orderId)) - .expectException(IllegalStateException.class); + .expectException(UnconfirmedOrderException.class); } @Test diff --git a/bootique/pom.xml b/bootique/pom.xml index 4ae8703074..4dd9ba4833 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -65,7 +65,6 @@ com.baeldung.bootique.App 0.23 - 2.4.3 diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index d6fc6fc2f7..33df8b107b 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -6,4 +6,5 @@ - [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines) - [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword) - [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching) -- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) \ No newline at end of file +- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) +- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications) diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index b945546c8a..ba3fd0802b 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -157,27 +157,24 @@ - - bintray - Groovy Bintray - https://dl.bintray.com/groovy/maven - - - never - - - false - - - - + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + + never + + + false + + + 1.0.0 2.4.0 1.1-groovy-2.4 - 3.9 - 1.8 3.8.1 1.2.3 2.5.7 diff --git a/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy new file mode 100644 index 0000000000..1d7527726e --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy @@ -0,0 +1,52 @@ +package com.baeldung.concatenate + +class Wonder { + + String numOfWonder = 'seven' + + String operator_plus() { + return 'The ' + numOfWonder + ' wonders of the world' + } + + String operator_left() { + return 'The ' << numOfWonder << ' wonders of ' << 'the world' + } + + String interpolation_one() { + return "The $numOfWonder wonders of the world" + + } + + String interpolation_two() { + return "The ${numOfWonder} wonders of the world" + } + + String multilineString() { + return """ + There are $numOfWonder wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + } + + String method_concat() { + return 'The '.concat(numOfWonder).concat(' wonders of the world') + + } + + String method_builder() { + return new StringBuilder() + .append('The ').append(numOfWonder).append(' wonders of the world') + } + + String method_buffer() { + return new StringBuffer() + .append('The ').append(numOfWonder).append(' wonders of the world') + } +} \ No newline at end of file diff --git a/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy new file mode 100644 index 0000000000..5fc74abd69 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy @@ -0,0 +1,69 @@ +package com.baeldung.concatenate + +import org.junit.Before +import org.junit.Test + +import static org.junit.Assert.* + +class WonderUnitTest { + + static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world" + + Wonder wonder + + @Before + void before() { + wonder = new Wonder() + } + + @Test + void whenUsingOperatorPlus_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus()) + } + + @Test + void whenUsingOperatorLeft_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left()) + } + + @Test + void whenUsingInterpolationOne_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one()) + } + + @Test + void whenUsingInterpolationTwo_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two()) + } + + @Test + void whenUsingMultiline_thenConcatCorrectly() { + def expectedMultiline = """ + There are seven wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + assertEquals(expectedMultiline, wonder.multilineString()) + } + + @Test + void whenUsingMethodConcat_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat()) + } + + @Test + void whenUsingMethodBuilder_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder()) + } + + @Test + void whenUsingMethodBuffer_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer()) + } +} diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java new file mode 100644 index 0000000000..71e2840f45 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java @@ -0,0 +1,45 @@ +package com.baeldung.array.looping; + +public class LoopDiagonally { + + + public String loopDiagonally(String[][] twoDArray) { + + int length = twoDArray.length; + int diagonalLines = (length + length) - 1; + int itemsInDiagonal = 0; + int midPoint = (diagonalLines / 2) + 1; + StringBuilder output = new StringBuilder(); + + for (int i = 1; i <= diagonalLines; i++) { + + StringBuilder items = new StringBuilder(); + int rowIndex; + int columnIndex; + + if (i <= midPoint) { + itemsInDiagonal++; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (i - j) - 1; + columnIndex = j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } else { + itemsInDiagonal--; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (length - 1) - j; + columnIndex = (i - length) + j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } + + if (i != diagonalLines) { + output.append(items).append(" "); + } else { + output.append(items); + } + } + + return output.toString(); + } +} diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java new file mode 100644 index 0000000000..df6079270b --- /dev/null +++ b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java @@ -0,0 +1,20 @@ +package com.baeldung.array.looping; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class LoopDiagonallyTest { + + @Test + public void twoArrayIsLoopedDiagonallyAsExpected() { + + LoopDiagonally loopDiagonally = new LoopDiagonally(); + String[][] twoDArray = {{"a", "b", "c"}, + {"d", "e", "f"}, + {"g", "h", "i"}}; + + String output = loopDiagonally.loopDiagonally(twoDArray); + assertEquals("a db gec hf i", output); + } +} \ No newline at end of file diff --git a/core-java-modules/README.md b/core-java-modules/README.md index 7a7d0a7a1b..9ce6057f32 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -3,3 +3,4 @@ - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) - [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) - [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) diff --git a/core-java-modules/core-java-10/README.md b/core-java-modules/core-java-10/README.md index f0a25712a7..8fb4f8a7dd 100644 --- a/core-java-modules/core-java-10/README.md +++ b/core-java-modules/core-java-10/README.md @@ -5,3 +5,4 @@ - [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md new file mode 100644 index 0000000000..6f8f95970e --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md new file mode 100644 index 0000000000..4514fd1a2b --- /dev/null +++ b/core-java-modules/core-java-12/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index d53b731878..245fa93ba7 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -6,3 +6,4 @@ - [Anonymous Classes in Java](http://www.baeldung.com/) - [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments) +- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index cc184de529..07bb3b7543 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -9,7 +9,6 @@ core-java-8-2 jar - com.baeldung parent-java @@ -17,19 +16,18 @@ ../../parent-java - - UTF-8 - 1.8 - 1.8 - 64.2 - - com.ibm.icu icu4j ${icu.version} + + org.assertj + assertj-core + ${assertj.version} + test + @@ -44,6 +42,13 @@ - + + + UTF-8 + 1.8 + 1.8 + 64.2 + 3.12.2 + diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java new file mode 100644 index 0000000000..ea63409c88 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.bifunction; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BiFunctionalInterfacesUnitTest { + @Test + public void givenStreamValues_whenMappedToNewValues() { + List mapped = Stream.of("hello", "world") + .map(word -> word + "!") + .collect(Collectors.toList()); + + assertThat(mapped).containsExactly("hello!", "world!"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingOperation() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> b + "-" + a); + + assertThat(result).isEqualTo("world-hello-"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingLambda_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> combineWithoutTrailingDash(a, b)); + + assertThat(result).isEqualTo("world-hello"); + } + + private String combineWithoutTrailingDash(String a, String b) { + if (a.isEmpty()) { + return b; + } + return b + "-" + a; + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingMethodReference_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", this::combineWithoutTrailingDash); + + assertThat(result).isEqualTo("world-hello"); + } + + @Test + public void givenTwoLists_whenCombined() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = new ArrayList<>(); + for (int i=0; i < list1.size(); i++) { + result.add(list1.get(i) + list2.get(i)); + } + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + @Test + public void givenTwoLists_whenCombinedWithGeneralPurposeCombiner() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = listCombiner(list1, list2, (a, b) -> a + b); + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + private static List listCombiner(List list1, + List list2, + BiFunction combiner) { + List result = new ArrayList<>(); + for (int i = 0; i < list1.size(); i++) { + result.add(combiner.apply(list1.get(i), list2.get(i))); + } + return result; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, (a, b) -> a > b); + + assertThat(result).containsExactly(true, true, false); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionByMethodReference() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, this::firstIsGreaterThanSecond); + + assertThat(result).containsExactly(true, true, false); + } + + private boolean firstIsGreaterThanSecond(Double a, Float b) { + return a > b; + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunction() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, (a, b) -> a.equals(b)); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunctionWithMethodReference() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, Float::equals); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithCompareTo() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, Double::compareTo); + + assertThat(result).containsExactly(1, 1, -1); + } + + /** + * Allows you to to pass in a lambda or method reference and then + * get access to the BiFunction it is meant to become + */ + private static BiFunction asBiFunction(BiFunction function) { + return function; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithComposedBiFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, + asBiFunction(Double::compareTo) + .andThen(i -> i > 0)); + + assertThat(result).containsExactly(true, true, false); + } +} diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index d11d2debce..b2ae48ea11 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -40,3 +40,4 @@ - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) - [Method References in Java](https://www.baeldung.com/java-method-references) - [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index c09c970e07..28182e515b 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -175,7 +175,6 @@ - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java new file mode 100644 index 0000000000..7a9f62341e --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java @@ -0,0 +1,34 @@ +package com.baeldung.java_8_features.groupingby; + +public class Tuple { + + private BlogPostType type; + private String author; + + public Tuple(BlogPostType type, String author) { + super(); + this.type = type; + this.author = author; + } + + public BlogPostType getType() { + return type; + } + + public void setType(BlogPostType type) { + this.type = type; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; + } +} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index bd7943c77b..bf594610bb 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -259,4 +259,15 @@ public class OptionalUnitTest { LOG.debug("Getting default value..."); return "Default Value"; } + +// Uncomment code when code base is compatiable with Java 11 +// @Test +// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { +// Optional opt = Optional.of("Baeldung"); +// assertFalse(opt.isEmpty()); +// +// opt = Optional.ofNullable(null); +// assertTrue(opt.isEmpty()); +// } + } \ No newline at end of file diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml index b713c196b5..23db608abc 100644 --- a/core-java-modules/core-java-arrays/pom.xml +++ b/core-java-modules/core-java-arrays/pom.xml @@ -389,7 +389,7 @@ - 3.8.1 + 3.9 1.19 1.19 diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java deleted file mode 100644 index 36cfc88b95..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.array; - -import java.util.Arrays; -import java.util.Scanner; - -public class JaggedArray { - - int[][] shortHandFormInitialization() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - return jaggedArr; - } - - int[][] declarationAndThenInitialization() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[] { 1, 2 }; - jaggedArr[1] = new int[] { 3, 4, 5 }; - jaggedArr[2] = new int[] { 6, 7, 8, 9 }; - return jaggedArr; - } - - int[][] declarationAndThenInitializationUsingUserInputs() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[2]; - jaggedArr[1] = new int[3]; - jaggedArr[2] = new int[4]; - initializeElements(jaggedArr); - return jaggedArr; - } - - void initializeElements(int[][] jaggedArr) { - Scanner sc = new Scanner(System.in); - for (int outer = 0; outer < jaggedArr.length; outer++) { - for (int inner = 0; inner < jaggedArr[outer].length; inner++) { - jaggedArr[outer][inner] = sc.nextInt(); - } - } - } - - void printElements(int[][] jaggedArr) { - for (int index = 0; index < jaggedArr.length; index++) { - System.out.println(Arrays.toString(jaggedArr[index])); - } - } - - int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { - return jaggedArr[index]; - } - -} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java new file mode 100644 index 0000000000..4e01b99a14 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java @@ -0,0 +1,83 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class MultiDimensionalArray { + + int[][] shortHandFormInitialization() { + int[][] multiDimensionalArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitialization() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[] { 1, 2 }; + multiDimensionalArray[1] = new int[] { 3, 4, 5 }; + multiDimensionalArray[2] = new int[] { 6, 7, 8, 9 }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[2]; + multiDimensionalArray[1] = new int[3]; + multiDimensionalArray[2] = new int[4]; + initializeElements(multiDimensionalArray); + return multiDimensionalArray; + } + + void initializeElements(int[][] multiDimensionalArray) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < multiDimensionalArray.length; outer++) { + for (int inner = 0; inner < multiDimensionalArray[outer].length; inner++) { + multiDimensionalArray[outer][inner] = sc.nextInt(); + } + } + } + + void initialize2DArray(int[][] multiDimensionalArray) { + for (int[] array : multiDimensionalArray) { + Arrays.fill(array, 7); + } + } + + void printElements(int[][] multiDimensionalArray) { + for (int index = 0; index < multiDimensionalArray.length; index++) { + System.out.println(Arrays.toString(multiDimensionalArray[index])); + } + } + + int[] getElementAtGivenIndex(int[][] multiDimensionalArray, int index) { + return multiDimensionalArray[index]; + } + + int[] findLengthOfElements(int[][] multiDimensionalArray) { + int[] arrayOfLengths = new int[multiDimensionalArray.length]; + for (int i = 0; i < multiDimensionalArray.length; i++) { + arrayOfLengths[i] = multiDimensionalArray[i].length; + } + return arrayOfLengths; + } + + Integer[] findLengthOfElements(Integer[][] multiDimensionalArray) { + return Arrays.stream(multiDimensionalArray) + .map(array -> array.length) + .toArray(Integer[]::new); + } + + int[][] copy2DArray(int[][] arrayOfArrays) { + int[][] copied2DArray = new int[arrayOfArrays.length][]; + for (int i = 0; i < arrayOfArrays.length; i++) { + int[] array = arrayOfArrays[i]; + copied2DArray[i] = Arrays.copyOf(array, array.length); + } + return copied2DArray; + } + + Integer[][] copy2DArray(Integer[][] arrayOfArrays) { + return Arrays.stream(arrayOfArrays) + .map(array -> Arrays.copyOf(array, array.length)) + .toArray(Integer[][]::new); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java new file mode 100644 index 0000000000..62a1a0ee58 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java @@ -0,0 +1,27 @@ +package com.baeldung.array; + +import org.apache.commons.lang3.ArrayUtils; + +public class RemoveElementFromAnArray { + + public int[] removeAnElementWithAGivenIndex(int[] array, int index) { + return ArrayUtils.remove(array, index); + } + + public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) { + return ArrayUtils.removeAll(array, indicies); + } + + public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) { + return ArrayUtils.removeElement(array, element); + } + + public int[] removeAllGivenElements(int[] array, int... elements) { + return ArrayUtils.removeElements(array, elements); + } + + public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) { + return ArrayUtils.removeAllOccurences(array, element); + } + +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java new file mode 100644 index 0000000000..ec612fd53b --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -0,0 +1,71 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; + +public class SortedArrayChecker { + boolean isSorted(int[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2] > array[length - 1]) + return false; + + return isSorted(array, length - 1); + } + + boolean isSorted(int[] array) { + for (int i = 0; i < array.length - 1; i++) { + if (array[i] > array[i + 1]) + return false; + } + + return true; + } + + boolean isSorted(String[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].compareTo(array[length - 1]) > 0) + return false; + + return isSorted(array, length - 1); + } + +boolean isSorted(String[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].compareTo(array[i + 1]) > 0) + return false; + } + + return true; +} + + boolean isSortedByName(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getName().compareTo(array[i + 1].getName()) > 0) + return false; + } + + return true; + } + +boolean isSortedByAge(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getAge() > (array[i + 1].getAge())) + return false; + } + + return true; +} + + boolean isSortedByAge(Employee[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].getAge() > array[length - 1].getAge()) + return false; + + return isSortedByAge(array, length - 1); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java index a7592574d9..eba39d5716 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java @@ -6,6 +6,7 @@ public class Employee implements Serializable { private static final long serialVersionUID = -2454619097207585825L; private int id; private String name; + private int age; public Employee() { } @@ -15,10 +16,24 @@ public class Employee implements Serializable { this.name = name; } + public Employee(int id, String name, int age) { + this.id = id; + this.name = name; + this.age = age; + } + + public int getAge() { + return age; + } + public int getId() { return id; } + public void setAge(int age) { + this.age = age; + } + public void setId(int id) { this.id = id; } diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java deleted file mode 100644 index a4dd7e25c3..0000000000 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.array; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.PrintStream; - -import org.junit.Test; - -public class JaggedArrayUnitTest { - - private JaggedArray obj = new JaggedArray(); - - @Test - public void whenInitializedUsingShortHandForm_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { - InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); - System.setIn(is); - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); - System.setIn(System.in); - } - - @Test - public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); - assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); - assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); - } - - @Test - public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - obj.printElements(jaggedArr); - assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); - System.setOut(System.out); - } - -} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java new file mode 100644 index 0000000000..8980eaa9dc --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class MultiDimensionalArrayUnitTest { + + private MultiDimensionalArray obj = new MultiDimensionalArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenMultiDimensionalArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(multiDimensionalArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(multiDimensionalArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(multiDimensionalArr, 2)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(multiDimensionalArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysFill_thenVerifyInitialize2DArray() { + int[][] multiDimensionalArr = new int[3][]; + multiDimensionalArr[0] = new int[2]; + multiDimensionalArr[1] = new int[3]; + multiDimensionalArr[2] = new int[4]; + obj.initialize2DArray(multiDimensionalArr); + assertArrayEquals(new int[][] {{7,7}, {7,7,7}, {7,7,7,7}}, multiDimensionalArr); + } + + @Test + public void givenMultiDimensionalArray_whenUsingIteration_thenVerifyFindLengthOfElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyFindLengthOfElements() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new Integer[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysCopyOf_thenVerifyCopy2DArray() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyCopy2DArray() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java new file mode 100644 index 0000000000..ea52cd17d9 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.array; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.api.Test; + +class RemoveElementFromAnArrayUnitTest { + + private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray(); + private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 }; + + @Test + void testRemoveAnElementWithAGivenIndex() { + int index = 2; + int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index])); + } + + @Test + void testRemoveAllElementsWithGivenIndices() { + int first = 0; + int last = inputArray.length - 1; + int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last])); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() { + int index = 2; + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAnElementWithAGivenIndex(null, index); + }); + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAllElementsWithGivenIndices(null, index); + }); + } + + @Test + void testRemoveFirstOccurrenceOfGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element); + + int indexInInputArray = ArrayUtils.indexOf(inputArray, element); + int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element); + assertFalse(indexInInputArray == indexInModifiedArray); + } + + @Test + void testRemoveAllGivenElements() { + int duplicateElement = 40; + int[] elements = new int[] { duplicateElement, 10, 50 }; + int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements); + + assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement)); + assertFalse(ArrayUtils.contains(modifiedArray, elements[1])); + assertFalse(ArrayUtils.contains(modifiedArray, elements[2])); + } + + @Test + void testRemoveAllOccurrencesOfAGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element); + + assertFalse(ArrayUtils.contains(modifiedArray, element)); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ReturnsNull() { + int element = 20; + + assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element)); + assertEquals(null, sut.removeAllGivenElements(null, element)); + assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element)); + + } + +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java new file mode 100644 index 0000000000..29866a3c22 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortedArrayCheckerUnitTest { + + private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9}; + private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7}; + + private static final String[] STRING_SORTED = {"abc", "cde", "fgh"}; + private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"}; + + private final Employee[] EMPLOYEES_SORTED_BY_NAME = { + new Employee(1, "Carlos", 26), + new Employee(2, "Daniel", 31), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = { + new Employee(1, "Daniel", 31), + new Employee(2, "Carlos", 26), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_SORTED_BY_AGE = { + new Employee(1, "Carlos", 26), + new Employee(2, "Marta", 27), + new Employee(3, "Daniel", 31)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { + new Employee(1, "Marta", 27), + new Employee(2, "Carlos", 26), + new Employee(3, "Daniel", 31)}; + + private SortedArrayChecker sortedArrayChecker; + + @Before + public void setup() { + sortedArrayChecker = new SortedArrayChecker(); + } + + @Test + public void givenIntegerArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED, INTEGER_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED, INTEGER_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenStringArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(STRING_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(STRING_SORTED, STRING_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED, STRING_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java index ecf68e0b2c..5f7fe356c5 100644 --- a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java +++ b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java @@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest { @Test(expected = UnsupportedOperationException.class) public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); + final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); unmodifiableList.add("four"); } diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2e09e920dc..618b4e932c 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -10,3 +10,4 @@ - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 4435f8b151..101ed79de0 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -14,30 +14,31 @@ - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - com.google.code.gson - gson - 2.8.5 - - - commons-lang - commons-lang - 2.6 - + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + com.google.code.gson + gson + ${gson.version} + + + commons-lang + commons-lang + ${commons-lang.version} + 4.3 27.1-jre + 2.8.5 \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index a3ac7aa88a..5d41909ed3 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -72,7 +72,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-concurrency-basic/README.md b/core-java-modules/core-java-concurrency-basic/README.md index 6fa702fbe7..c498bed315 100644 --- a/core-java-modules/core-java-concurrency-basic/README.md +++ b/core-java-modules/core-java-concurrency-basic/README.md @@ -17,3 +17,4 @@ - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety) - [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread) +- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index aea4bef6a7..96b3ef76f7 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/pom.xml @@ -45,8 +45,6 @@ - - 3.5 3.6.1 1.7.0 diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index 27aae4ea6c..ea3bbe44f3 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/pom.xml @@ -62,7 +62,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md new file mode 100644 index 0000000000..5338789a2f --- /dev/null +++ b/core-java-modules/core-java-exceptions/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 37f65882c3..2e5200944a 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -14,15 +14,11 @@ ../../parent-java - - 3.9 - - junit junit - 4.12 + ${junit.version} test @@ -32,4 +28,8 @@ + + 3.9 + + diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 44c703ee68..1a133d2cbe 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -248,7 +248,6 @@ - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index 6a41ec0d1a..059075318a 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -11,6 +11,14 @@ 1.0 + + + com.baeldung.servicemodule + servicemodule + 1.0 + + + @@ -19,12 +27,4 @@ - - - - com.baeldung.servicemodule - servicemodule - 1.0 - - diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 828fe7de6a..757d9229df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -2,17 +2,18 @@ - - com.baeldung.decoupling-pattern2 - decoupling-pattern2 - 1.0-SNAPSHOT - 4.0.0 com.baeldung.consumermodule consumermodule 1.0 + + com.baeldung.decoupling-pattern2 + decoupling-pattern2 + 1.0-SNAPSHOT + + com.baeldung.servicemodule diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 6c700cd005..b1860322a6 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -35,7 +35,6 @@ - 3.5 3.6.1 diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md new file mode 100644 index 0000000000..10b876735e --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/core-java-modules/core-java-lang-oop-2/README.md b/core-java-modules/core-java-lang-oop-2/README.md index 2e36d251ca..72c3c6742b 100644 --- a/core-java-modules/core-java-lang-oop-2/README.md +++ b/core-java-modules/core-java-lang-oop-2/README.md @@ -6,3 +6,4 @@ - [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors) - [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error) - [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) +- [Raw Types in Java](https://www.baeldung.com/raw-types-java) diff --git a/core-java-modules/core-java-lang-oop/pom.xml b/core-java-modules/core-java-lang-oop/pom.xml index c9bb3b3e5a..46003b132b 100644 --- a/core-java-modules/core-java-lang-oop/pom.xml +++ b/core-java-modules/core-java-lang-oop/pom.xml @@ -75,13 +75,7 @@ - - - 2.8.5 2.8.2 - - - 3.5 3.10.0 3.0.3 diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java index 3d50e85245..b78b5937e1 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java +++ b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java @@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount { this.balance = 0.0f; } } + +class BankAccountChainedConstructors extends BankAccount { + public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) { + this.name = name; + this.opened = opened; + this.balance = balance; + } + + public BankAccountChainedConstructors(String name) { + this(name, LocalDateTime.now(), 0.0f); + } +} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java index 2cd8832fbf..66c8520e34 100644 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java +++ b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.constructors; -import com.baeldung.constructors.*; +import com.google.common.collect.Comparators; +import org.junit.Test; -import java.util.logging.Logger; import java.time.LocalDateTime; import java.time.Month; +import java.util.ArrayList; +import java.util.logging.Logger; -import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; public class ConstructorUnitTest { final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName()); @@ -17,26 +16,28 @@ public class ConstructorUnitTest { @Test public void givenNoExplicitContructor_whenUsed_thenFails() { BankAccount account = new BankAccount(); - assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class); + assertThatThrownBy(() -> { + account.toString(); + }).isInstanceOf(Exception.class); } @Test public void givenNoArgumentConstructor_whenUsed_thenSucceeds() { BankAccountEmptyConstructor account = new BankAccountEmptyConstructor(); assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test public void givenParameterisedConstructor_whenUsed_thenSucceeds() { LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00); BankAccountParameterizedConstructor account = - new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); - + new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); + assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test @@ -47,7 +48,16 @@ public class ConstructorUnitTest { assertThat(account.getName()).isEqualTo(newAccount.getName()); assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened()); - + assertThat(newAccount.getBalance()).isEqualTo(0.0f); } + + @Test + public void givenChainedConstructor_whenUsed_thenMaintainsLogic() { + BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim"); + BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f); + + assertThat(account.getName()).isEqualTo(newAccount.getName()); + assertThat(account.getBalance()).isEqualTo(newAccount.getBalance()); + } } diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index e9169a5820..74936eac21 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -18,7 +18,6 @@ - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) - [Recursion In Java](http://www.baeldung.com/java-recursion) - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) - [Using Java Assertions](http://www.baeldung.com/java-assert) diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 45ccc8d0f5..8311636873 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/pom.xml @@ -75,9 +75,6 @@ 2.8.2 - - - 3.5 1.5.0-b01 diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index 550ebdb4ff..e2ee7b2fcc 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/pom.xml @@ -42,8 +42,6 @@ 1.5.0-b01 - 2.5 - 3.5 4.3.4.RELEASE diff --git a/core-java-modules/core-java-nio/README.md b/core-java-modules/core-java-nio/README.md index e73a9850ad..9034c3b3b1 100644 --- a/core-java-modules/core-java-nio/README.md +++ b/core-java-modules/core-java-nio/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Determine File Creating Date in Java](https://www.baeldung.com/file-creation-date-java) +- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date) diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index 36d6848998..31433e632f 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -8,9 +8,9 @@ jar - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java \ No newline at end of file diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md index 12a6fd1a56..b6848b5d33 100644 --- a/core-java-modules/core-java-optional/README.md +++ b/core-java-modules/core-java-optional/README.md @@ -2,4 +2,5 @@ ## Core Java Optional -### Relevant Articles: \ No newline at end of file +### Relevant Articles: +- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return) diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index f2478c2c87..eb981c0907 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -1,22 +1,14 @@ - 4.0.0 - - com.baeldung.core-java-modules - core-java-modules - 1.0.0-SNAPSHOT - - core-java-optional - 0.1.0-SNAPSHOT - jar - - - UTF-8 - 1.8 - 1.8 - 5.4.0.Final - 1.4.197 - 2.9.8 - + 4.0.0 + core-java-optional + 0.1.0-SNAPSHOT + jar + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + @@ -27,12 +19,12 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.fasterxml.jackson.core jackson-databind - ${jackson.databind.version} + ${jackson.version} @@ -50,4 +42,11 @@ + + + UTF-8 + 1.8 + 1.8 + 5.4.0.Final + \ No newline at end of file diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 85194b176e..f6c5ef04a5 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -68,7 +68,6 @@ - 3.5 4.1 4.01 diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java new file mode 100644 index 0000000000..8f022d2cc7 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java @@ -0,0 +1,40 @@ +package com.baeldung.core.pwd; + +import java.io.File; +import java.nio.file.FileSystems; +import java.nio.file.Paths; + +public final class CurrentDirectoryFetcher { + + public static void main(String[] args) { + System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties()); + + System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile()); + + System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems()); + + System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths()); + } + + public static String currentDirectoryUsingSystemProperties() { + return System.getProperty("user.dir"); + } + + public static String currentDirectoryUsingPaths() { + return Paths.get("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFileSystems() { + return FileSystems.getDefault() + .getPath("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFile() { + return new File("").getAbsolutePath(); + } + +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java new file mode 100644 index 0000000000..dbaad211d9 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java @@ -0,0 +1,34 @@ +package com.baeldung.core.pwd; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CurrentDirectoryFetcherTest { + + private static final String CURRENT_DIR = "core-java-os"; + + @Test + public void whenUsingSystemProperties_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaIoFile_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile() + .endsWith(CURRENT_DIR)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index f225a9554b..b9c9d30ac0 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/pom.xml @@ -23,11 +23,4 @@ - - - - 3.8.1 - - - diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index ed82a5209a..d3efb26fe8 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -43,7 +43,6 @@ - 3.8.1 1.60 1.11 diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index da27564d96..ab5f945114 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/pom.xml @@ -264,7 +264,6 @@ 23.0 - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index b32b5d5cd9..436a481803 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -37,7 +37,6 @@ - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) -- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 7942f3e7e2..2a2cb3a6af 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -13,7 +13,6 @@ ../../parent-java - commons-io @@ -114,7 +113,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -454,8 +453,6 @@ 2.8.2 - 3.9 - 2.5 3.6.1 1.0.3 0.4 @@ -472,7 +469,6 @@ 2.21.0 1.1 - 1.4.197 2.1.0.1 1.19 diff --git a/core-java-modules/multimodulemavenproject/daomodule/pom.xml b/core-java-modules/multimodulemavenproject/daomodule/pom.xml index a260e15e6d..e98c48aa76 100644 --- a/core-java-modules/multimodulemavenproject/daomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/daomodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.daomodule + daomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.daomodule - daomodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml index 1fd672d03e..b90a7ed068 100644 --- a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.entitymodule + entitymodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.entitymodule - entitymodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index 26e6a15b1e..1f44a1690c 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.mainappmodule + mainappmodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.mainappmodule - mainappmodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 3d56f1356b..ad347a4179 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -14,18 +14,25 @@ ../../ + + entitymodule + daomodule + userdaomodule + mainappmodule + + junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.2 + ${assertj-core.version} test @@ -49,14 +56,8 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 + 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 63968452db..d3543d5864 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -1,24 +1,16 @@ 4.0.0 + com.baeldung.userdaomodule + userdaomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.userdaomodule - userdaomodule - 1.0 - jar - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - @@ -33,6 +25,15 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + 9 9 diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index 169cd21f3e..380d94fbf1 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -18,9 +18,10 @@ org.slf4j slf4j-api - 1.7.25 + ${org.slf4j.version} + pre-jpms @@ -65,9 +66,9 @@ - + UTF-8 diff --git a/core-kotlin-io/pom.xml b/core-kotlin-io/pom.xml index a0b688a223..78b36626d6 100644 --- a/core-kotlin-io/pom.xml +++ b/core-kotlin-io/pom.xml @@ -22,7 +22,7 @@ org.junit.jupiter junit-jupiter - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -88,7 +88,7 @@ 1.3.30 - 5.4.2 + 5.4.2 2.27.0 1.9.12 3.10.0 diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 5de986b49e..e4d243360a 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -39,7 +39,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.github.kittinunf.fuel @@ -76,11 +76,9 @@ 3.6.1 - 3.8.1 1.1.1 5.2.0 3.10.0 - 1.4.197 1.15.0 3.3.0 1.16.1 diff --git a/couchbase/pom.xml b/couchbase/pom.xml index 31e6a53388..fc40749c61 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -69,7 +69,6 @@ 2.5.0 4.3.5.RELEASE - 3.5 diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index e19bce6e52..3ae5e8e41a 100644 Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 74e6d9593b..9964bf2bb4 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -7,6 +7,12 @@ custom-pmd jar http://maven.apache.org + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 3b73f9c21c..2cbab782ee 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { String className = node.getImage(); Objects.requireNonNull(className); + if (className.endsWith("SpringContextTest")) { + return data; + } + if (className.endsWith("Tests") || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { addViolation(data, node); diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 296704f546..e1d78e7ed6 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -115,7 +115,6 @@ - 3.5 3.3.6 6.10 diff --git a/dozer/pom.xml b/dozer/pom.xml index 5720001acf..8234eb4c79 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -26,7 +26,6 @@ - 3.5 5.5.1 diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index f49a51ea4b..e8b327e35f 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -8,6 +8,13 @@ 1.0-SNAPSHOT flyway-cdi-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + javax.enterprise @@ -51,6 +58,5 @@ 5.1.4 8.5.33 1.3.2 - 1.4.197 diff --git a/gson/pom.xml b/gson/pom.xml index a21d783c39..9d2cf630d0 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -64,7 +64,6 @@ 2.8.0 - 3.5 4.1 2.9.6 diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index a717023156..ecda3c9595 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -55,7 +55,6 @@ 24.0-jre - 3.5 4.1 diff --git a/guava/pom.xml b/guava/pom.xml index 1d37a79ab6..34eb7eafa6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -49,7 +49,6 @@ 24.0-jre - 3.5 3.6.1 diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index efcf0452e2..7dd54c8fc4 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -297,7 +297,6 @@ 19.0 - 3.5 1.10 4.1.4 @@ -305,7 +304,6 @@ 4.4.11 4.5.8 - 2.6 1.6.1 diff --git a/httpclient/pom.xml b/httpclient/pom.xml index def3a05816..8cd483cfc6 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -120,7 +120,6 @@ 19.0 - 3.5 1.10 4.1.4 diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 7bb3e98246..e08af2c40f 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -65,7 +65,6 @@ 1.5.8 0.20.7 - 2.6 2.7 1.5.8 1.5.8 diff --git a/jackson-2/README.md b/jackson-2/README.md index ee9f8458a0..d8c233a00e 100644 --- a/jackson-2/README.md +++ b/jackson-2/README.md @@ -9,4 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml) - [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) - +- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv) diff --git a/jackson-2/pom.xml b/jackson-2/pom.xml index 6a975f1de7..2fff1f8706 100644 --- a/jackson-2/pom.xml +++ b/jackson-2/pom.xml @@ -26,21 +26,21 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - 2.9.8 + ${jackson.version} com.fasterxml.jackson.dataformat jackson-dataformat-csv - 2.9.8 + ${jackson.version} com.fasterxml.jackson.datatype jackson-datatype-jsr310 - 2.9.8 + ${jackson.version} diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java new file mode 100644 index 0000000000..03d7c63e36 --- /dev/null +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.jackson.json.compare; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Comparator; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NumericNode; +import com.fasterxml.jackson.databind.node.TextNode; + +public class JsonCompareUnitTest { + + @Test + public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\", \"age\": 34 }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"age\": 34, \"fullName\": \"John Miles\" }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoSameListJsonDataObjects_whenCompared_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertEquals(actualObj1, actualObj2); + + } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomNumericNodeComparator_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"name\": \"John\",\"score\":5.0}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + NumericNodeComparator cmp = new NumericNodeComparator(); + + assertNotEquals(actualObj1, actualObj2); + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + + public class NumericNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { + Double d1 = ((NumericNode) o1).asDouble(); + Double d2 = ((NumericNode) o2).asDouble(); + if (d1.compareTo(d2) == 0) { + return 0; + } + } + return 1; + } + } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomTextNodeComparator_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"name\": \"JOHN\",\"score\":5}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + TextNodeComparator cmp = new TextNodeComparator(); + + assertNotEquals(actualObj1, actualObj2); + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + + public class TextNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) { + String s1 = ((TextNode) o1).asText(); + String s2 = ((TextNode) o2).asText(); + if (s1.equalsIgnoreCase(s2)) { + return 0; + } + } + return 1; + } + } +} diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 5023ad87b6..05c1ef4595 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 4230420132..146f274380 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); @@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject = new MyDto(); diff --git a/jackson/pom.xml b/jackson/pom.xml index 948248d255..8a083525a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 31fead3c42..614f20f186 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -10,4 +10,7 @@ - [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string) - [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [Array to String Conversions](https://www.baeldung.com/java-array-to-string) -- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) \ No newline at end of file +- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) +- [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) +- [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) +- [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list) diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index ee7221b25e..24d918d105 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -33,7 +33,6 @@ - 3.5 4.1 3.6.1 diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java index f2c80429d1..0283191b74 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.java.collections; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml index 5f27eaa2d8..e242a8655e 100644 --- a/java-collections-maps-2/pom.xml +++ b/java-collections-maps-2/pom.xml @@ -54,7 +54,6 @@ 3.0.2 8.1.0 1.2.0 - 3.8.1 3.11.1 diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml index b5eba31437..83cc97a21e 100644 --- a/java-collections-maps/pom.xml +++ b/java-collections-maps/pom.xml @@ -44,7 +44,6 @@ - 3.5 4.1 4.01 1.7.0 diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml index 2f861ff5f4..c1419514ef 100644 --- a/java-dates-2/pom.xml +++ b/java-dates-2/pom.xml @@ -25,7 +25,7 @@ commons-validator commons-validator - 1.6 + ${commons-validator.version} @@ -63,6 +63,7 @@ 3.6.1 2.10 + 1.6 1.9 1.9 diff --git a/java-dates/pom.xml b/java-dates/pom.xml index d4f690d894..3fddf3f0f8 100644 --- a/java-dates/pom.xml +++ b/java-dates/pom.xml @@ -74,8 +74,6 @@ - - 3.5 2.10 3.6.1 diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 9b8356714f..4d4e2ba3b3 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -72,8 +72,6 @@ 8.0 2.3 18.0.0.1 - - 3.2.2 diff --git a/java-math/pom.xml b/java-math/pom.xml index 159d053df3..f71577b707 100644 --- a/java-math/pom.xml +++ b/java-math/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -63,6 +63,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/java-numbers-2/.gitignore b/java-numbers-2/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-numbers-2/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml new file mode 100644 index 0000000000..57f1154f53 --- /dev/null +++ b/java-numbers-2/pom.xml @@ -0,0 +1,135 @@ + + 4.0.0 + java-numbers-2 + 0.1.0-SNAPSHOT + java-numbers-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers-2 + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + 1.8 + 1.8 + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 3.6.1 + 1.0.3 + 3.5 + + 3.6.1 + + 1.7.21 + 1.1.7 + + 2.21.0 + 3.0.0-M1 + 3.0.2 + + diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java new file mode 100644 index 0000000000..2001f39359 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.lossyconversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Test; + +public class ConversionTechniquesUnitTest { + + @Test + public void testPrimitiveConversion() { + + long longNum = 24; + short shortNum = (short) longNum; + assertEquals(24, shortNum); + + double doubleNum = 15.6; + int integerNum = (int) doubleNum; + assertEquals(15, integerNum); + + long largeLongNum = 32768; + short minShortNum = (short) largeLongNum; + assertEquals(-32768, minShortNum); + + long smallLongNum = -32769; + short maxShortNum = (short) smallLongNum; + assertEquals(32767, maxShortNum); + + long maxLong = Long.MAX_VALUE; + int minInt = (int) maxLong; + assertEquals(-1, minInt); + + long minLong = Long.MIN_VALUE; + int maxInt = (int) minLong; + assertEquals(0, maxInt); + } + + @Test + public void testWrapperToPrimitiveConversion() { + + Float floatNum = 17.564f; + long longNum = floatNum.longValue(); + assertEquals(17, longNum); + + Double doubleNum = 15.9999; + longNum = doubleNum.longValue(); + assertEquals(15, longNum); + } + + @Test + public void testWrapperToPrimitiveConversionUsingMathRound() { + + Double doubleNum = 15.9999; + long longNum = Math.round(doubleNum); + assertEquals(16, longNum); + } + + @Test + public void testWrapperConversion() { + + Double doubleNum = 10.3; + double dbl = doubleNum.doubleValue(); //unboxing + int intgr = (int) dbl; //downcasting + Integer intNum = Integer.valueOf(intgr); + assertEquals(Integer.valueOf(10), intNum); + } + +} diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index daed356f66..ac3ca2680f 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -121,7 +121,6 @@ 3.6.1 1.0.3 - 3.5 3.6.1 diff --git a/java-streams-2/README.md b/java-streams-2/README.md index 83ef97686f..851d3d71e2 100644 --- a/java-streams-2/README.md +++ b/java-streams-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) - +- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) +- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) diff --git a/java-streams/pom.xml b/java-streams/pom.xml index b0c56ecdf9..bd0123e01d 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -106,7 +106,6 @@ - 3.5 0.9.0 1.15 0.6.5 diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 85832fde37..c6d4f0222a 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -3,3 +3,5 @@ - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java similarity index 93% rename from java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java index b458fae79b..3ebee9b5d1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.string.multiline; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index e3d8a430d9..096b1bb229 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -88,7 +88,6 @@ 3.9.1 2.21.0 1.3.3 - 2.6 4.0.1 diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 3ed6d9b21a..d575f12c7b 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -130,8 +130,6 @@ 2.3 3.0.2 - 2.5 - 3.5 1.0.0 1.1 diff --git a/jee-7/pom.xml b/jee-7/pom.xml index d389b57cd5..9432801fd9 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -519,11 +519,9 @@ 1.13 2.25 1.0.0.Final - 2.6 4.2.3.RELEASE 2.21.0 1.1.2 - 2.4 2.2.14 4.5 2.0.1.Final diff --git a/jee-kotlin/README.md b/jee-kotlin/README.md new file mode 100644 index 0000000000..7d843af9ea --- /dev/null +++ b/jee-kotlin/README.md @@ -0,0 +1 @@ +### Relevant Articles: diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml new file mode 100644 index 0000000000..17163ba23c --- /dev/null +++ b/jee-kotlin/pom.xml @@ -0,0 +1,286 @@ + + + + 4.0.0 + jee-kotlin + jee-kotlin + war + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin.version} + test + + + junit + junit + ${junit.version} + test + + + javax + javaee-api + ${javaee-api.version} + jar + provided + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + test + + + org.jboss.arquillian.junit + arquillian-junit-container + ${arquillian_core.version} + test + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-depchain + ${shrinkwrap.version} + pom + test + + + org.jboss.arquillian.extension + arquillian-rest-client-impl-jersey + ${arquillian-rest-client.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + src/main/kotlin + src/test/kotlin + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + webapp + kotlin + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + compile + compile + + compile + + + + testCompile + test-compile + + testCompile + + + + + + + + + + + org.jboss.arquillian + arquillian-bom + ${arquillian_core.version} + import + pom + + + org.jboss.arquillian.extension + arquillian-drone-bom + ${arquillian-drone-bom.version} + pom + import + + + + + + + wildfly-managed-arquillian + + true + + + + org.wildfly + wildfly-arquillian-container-embedded + ${wildfly.version} + + + org.wildfly + wildfly-embedded + ${wildfly.version} + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + ${maven-dependency-plugin.version} + + + unpack + process-test-classes + + unpack + + + + + org.wildfly + wildfly-dist + ${wildfly.version} + zip + false + target + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + always + + org.jboss.logmanager.LogManager + ${project.basedir}/target/wildfly-${wildfly.version} + ${project.basedir}/target/wildfly-${wildfly.version}/modules + + false + + + + + + + wildfly-remote-arquillian + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-json-p-provider + ${resteasy.version} + test + + + org.wildfly.arquillian + wildfly-arquillian-container-remote + 2.2.0.Final + test + + + + + + + UTF-8 + false + 8.0 + + + 1.3.41 + official + true + + + 8.2.1.Final + 2.21.0 + 3.1.1 + + 1.4.1.Final + 2.0.1.Final + 1.0.0.Alpha4 + + 3.8.0.Final + 3.1.3 + + + diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt new file mode 100644 index 0000000000..07f54a39d1 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt @@ -0,0 +1,22 @@ +package com.baeldung.jeekotlin.entity + +import com.fasterxml.jackson.annotation.JsonProperty +import javax.persistence.* + +@Entity +data class Student constructor ( + + @SequenceGenerator(name = "student_id_seq", sequenceName = "student_id_seq", allocationSize = 1) + @GeneratedValue(generator = "student_id_seq", strategy = GenerationType.SEQUENCE) + @Id + var id: Long?, + + var firstName: String, + + var lastName: String + +) { + constructor() : this(null, "", "") + + constructor(firstName: String, lastName: String) : this(null, firstName, lastName) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt new file mode 100644 index 0000000000..12511ed320 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt @@ -0,0 +1,9 @@ +package com.baeldung.jeekotlin.rest + +import javax.ws.rs.ApplicationPath +import javax.ws.rs.core.Application + +@ApplicationPath("/") +class ApplicationConfig : Application() { + override fun getClasses() = setOf(StudentResource::class.java) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt new file mode 100644 index 0000000000..91fa3ff62b --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt @@ -0,0 +1,42 @@ +package com.baeldung.jeekotlin.rest + +import com.baeldung.jeekotlin.entity.Student +import com.baeldung.jeekotlin.service.StudentService +import javax.inject.Inject +import javax.ws.rs.* +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response + +@Path("/student") +open class StudentResource { + + @Inject + private lateinit var service: StudentService + + @POST + open fun create(student: Student): Response { + service.create(student) + return Response.ok().build() + } + + @GET + @Path("/{id}") + open fun read(@PathParam("id") id: Long): Response { + val student = service.read(id) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @PUT + open fun update(student: Student): Response { + service.update(student) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @DELETE + @Path("/{id}") + open fun delete(@PathParam("id") id: Long): Response { + service.delete(id) + return Response.noContent().build() + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt new file mode 100644 index 0000000000..3977a45e96 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt @@ -0,0 +1,21 @@ +package com.baeldung.jeekotlin.service + +import com.baeldung.jeekotlin.entity.Student +import javax.ejb.Stateless +import javax.persistence.EntityManager +import javax.persistence.PersistenceContext + +@Stateless +open class StudentService { + + @PersistenceContext + private lateinit var entityManager: EntityManager + + open fun create(student: Student) = entityManager.persist(student) + + open fun read(id: Long): Student? = entityManager.find(Student::class.java, id) + + open fun update(student: Student) = entityManager.merge(student) + + open fun delete(id: Long) = entityManager.remove(read(id)) +} \ No newline at end of file diff --git a/jee-kotlin/src/main/resources/META-INF/persistence.xml b/jee-kotlin/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..daac86868b --- /dev/null +++ b/jee-kotlin/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + + java:jboss/datasources/ExampleDS + + com.enpy.entity.Student + + + + + + + + diff --git a/jee-kotlin/src/main/webapp/WEB-INF/beans.xml b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..ae0f4bf2ee --- /dev/null +++ b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java new file mode 100644 index 0000000000..b91b47cb1f --- /dev/null +++ b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java @@ -0,0 +1,108 @@ +package com.baeldung.jeekotlin; + +import com.baeldung.jeekotlin.entity.Student; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Filters; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URISyntaxException; +import java.net.URL; + +import static org.junit.Assert.assertEquals; + +@RunWith(Arquillian.class) +public class StudentResourceIntegrationTest { + + @Deployment + public static WebArchive createDeployment() { + JavaArchive[] kotlinRuntime = Maven.configureResolver() + .workOffline() + .withMavenCentralRepo(true) + .withClassPathResolution(true) + .loadPomFromFile("pom.xml") + .resolve("org.jetbrains.kotlin:kotlin-stdlib") + .withTransitivity() + .as(JavaArchive.class); + + return ShrinkWrap.create(WebArchive.class, "kotlin.war") + .addPackages(true, Filters.exclude(".*Test*"), + "com.baeldung.jeekotlin" + ) + .addAsLibraries(kotlinRuntime) + .addAsResource("META-INF/persistence.xml") + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + @Test + @RunAsClient + public void when_post__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + String student = new ObjectMapper().writeValueAsString(new Student("firstName", "lastName")); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .post(Entity.json(student)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_get__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request(MediaType.APPLICATION_JSON) + .get(); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_put__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + Student student = new Student("firstName", "lastName"); + student.setId(1L); + String studentJson = new ObjectMapper().writeValueAsString(student); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .put(Entity.json(studentJson)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_delete__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request() + .delete(); + + assertEquals(204, response.getStatus()); + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/test/resources/arquillian.xml b/jee-kotlin/src/test/resources/arquillian.xml new file mode 100644 index 0000000000..5e6d7c54e8 --- /dev/null +++ b/jee-kotlin/src/test/resources/arquillian.xml @@ -0,0 +1,22 @@ + + + + + target/wildfly-8.2.1.Final + standalone.xml + true + 9990 + + + + + + 127.0.0.1 + 9990 + admin + pass + true + + + + \ No newline at end of file diff --git a/jersey/pom.xml b/jersey/pom.xml index a3adb4cf5a..708b36ce41 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -80,7 +80,6 @@ 2.26 - 3.2.0 diff --git a/jhipster/README.md b/jhipster/README.md deleted file mode 100644 index 289bfac754..0000000000 --- a/jhipster/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Relevant articles: - -- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) -- [Intro to JHipster](http://www.baeldung.com/jhipster) -- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) -- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles) diff --git a/jsf/pom.xml b/jsf/pom.xml index 19f1265250..31362a8809 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -99,9 +99,6 @@ 2.2.14 3.0.0 - - 2.6 - 6.2 diff --git a/jws/pom.xml b/jws/pom.xml index 2c89b687f8..5c19c887d3 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -34,6 +34,7 @@ + ${project.artifactId} org.apache.maven.plugins @@ -78,12 +79,10 @@ - ${project.artifactId} 3.0.2 - 3.0.0 1.6.0 1.6.0 diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index b75c77f358..e252329426 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -94,7 +94,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -184,7 +184,6 @@ 1.1.1 5.2.0 3.10.0 - 1.4.197 0.10.4 1.9.3 diff --git a/kotlin-quasar/README.md b/kotlin-quasar/README.md new file mode 100644 index 0000000000..b3b84e0446 --- /dev/null +++ b/kotlin-quasar/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar) diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index 44feabd183..231b02b0c7 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -8,6 +8,12 @@ kotlin-quasar jar + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + org.jetbrains.kotlin @@ -45,6 +51,27 @@ junit 4.12 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + @@ -116,5 +143,7 @@ 0.8.0 1.3.31 + 1.7.21 + 1.1.7 diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt new file mode 100644 index 0000000000..b4d0288a64 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt @@ -0,0 +1,157 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.Actor +import co.paralleluniverse.actors.ActorRef +import co.paralleluniverse.actors.behaviors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.SuspendableCallable +import org.junit.Test +import org.slf4j.LoggerFactory +import java.lang.Exception + +class ActorsBehaviorTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsBehaviorTest::class.java) + } + + @Test + fun requestReplyHelper() { + data class TestMessage(val input: Int) : RequestMessage() + + val actor = object : Actor("requestReplyActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + LOG.info("Processing message: {}", msg) + + RequestReplyHelper.reply(msg, msg.input * 100) + } + } + } + + val actorRef = actor.spawn() + + val result = RequestReplyHelper.call(actorRef, TestMessage(50)) + LOG.info("Received reply: {}", result) + } + + @Test + fun server() { + val actor = ServerActor(object : AbstractServerHandler() { + @Suspendable + override fun handleCall(from: ActorRef<*>?, id: Any?, m: Int?): String { + LOG.info("Called with message: {} from {} with ID {}", m, from, id) + return m.toString() ?: "None" + } + + @Suspendable + override fun handleCast(from: ActorRef<*>?, id: Any?, m: Float?) { + LOG.info("Cast message: {} from {} with ID {}", m, from, id) + } + }) + + val server = actor.spawn() + + LOG.info("Call result: {}", server.call(5)) + server.cast(2.5f) + + server.shutdown() + } + + interface Summer { + fun sum(a: Int, b: Int) : Int + } + + @Test + fun proxyServer() { + val actor = ProxyServerActor(false, object : Summer { + @Synchronized + override fun sum(a: Int, b: Int): Int { + Exception().printStackTrace() + LOG.info("Adding together {} and {}", a, b) + return a + b + } + }) + + val summerActor = actor.spawn() + + val result = (summerActor as Summer).sum(1, 2) + LOG.info("Result: {}", result) + + summerActor.shutdown() + } + + @Test + fun eventSource() { + val actor = EventSourceActor() + val eventSource = actor.spawn() + + eventSource.addHandler { msg -> + LOG.info("Sent message: {}", msg) + } + + val name = "Outside Value" + eventSource.addHandler { msg -> + LOG.info("Also Sent message: {} {}", msg, name) + } + + eventSource.send("Hello") + + eventSource.shutdown() + } + + @Test + fun finiteStateMachine() { + val actor = object : FiniteStateMachineActor() { + @Suspendable + override fun initialState(): SuspendableCallable> { + LOG.info("Starting") + return SuspendableCallable { lockedState() } + } + + @Suspendable + fun lockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Still locked") + lockedState() + } + "COIN" -> { + LOG.info("Unlocking...") + unlockedState() + } + else -> TERMINATE + } + } + } + + @Suspendable + fun unlockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Locking") + lockedState() + } + "COIN" -> { + LOG.info("Unlocked") + unlockedState() + } + else -> TERMINATE + } + } + } + } + + val actorRef = actor.spawn() + + listOf("PUSH", "COIN", "COIN", "PUSH", "PUSH").forEach { + LOG.info(it) + actorRef.sendSync(it) + } + + actorRef.shutdown() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt new file mode 100644 index 0000000000..819a149af3 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt @@ -0,0 +1,298 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.channels.Channels +import org.junit.Assert +import org.junit.Test +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ActorsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsTest::class.java) + } + + @Test + fun createNoopActor() { + val actor = object : Actor("noopActor", MailboxConfig(5, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + actor.spawn() + + println("Noop Actor: ${actor.get()}") + } + + @Test + fun registerActor() { + val actor = object : Actor("registerActor", null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register() + + val retrievedRef = ActorRegistry.getActor>("registerActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun registerActorNewName() { + val actor = object : Actor(null, null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register("renamedActor") + + val retrievedRef = ActorRegistry.getActor>("renamedActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun retrieveUnknownActor() { + val retrievedRef = ActorRegistry.getActor>("unknownActor", 1, TimeUnit.SECONDS) + + Assert.assertNull(retrievedRef) + } + + @Test + fun createSimpleActor() { + val actor = object : Actor("simpleActor", null) { + @Suspendable + override fun doRun(): Void? { + val msg = receive() + LOG.info("SimpleActor Received Message: {}", msg) + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + + actor.join() + } + + @Test + fun createLoopingActor() { + val actor = object : Actor("loopingActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("LoopingActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun actorBacklog() { + val actor = object : Actor("backlogActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog Actor Received: {}", receive()) + + try { + receive() + } catch (e: Throwable) { + LOG.info("==== Exception throws by receive() ====") + e.printStackTrace() + } + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + actorRef.send(2) + + try { + LOG.info("Backlog Actor: {}", actor.get()) + } catch (e: Exception) { + // Expected + LOG.info("==== Exception throws by get() ====") + e.printStackTrace() + } + } + + @Test + fun actorBacklogTrySend() { + val actor = object : Actor("backlogTrySendActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog TrySend Actor Received: {}", receive()) + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(1)) + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(2)) + + actor.join() + } + + @Test + fun actorTimeoutReceive() { + val actor = object : Actor("TimeoutReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("Timeout Actor Received: {}", receive(500, TimeUnit.MILLISECONDS)) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + + @Test + fun actorNonBlockingReceive() { + val actor = object : Actor("NonBlockingReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("NonBlocking Actor Received #1: {}", tryReceive()) + TimeUnit.MILLISECONDS.sleep(500) + LOG.info("NonBlocking Actor Received #2: {}", tryReceive()) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + @Test + fun evenActor() { + val actor = object : Actor("EvenActor", null) { + @Suspendable + override fun filterMessage(m: Any?): Int? { + return when (m) { + is Int -> { + if (m % 2 == 0) { + m * 10 + } else { + null + } + } + else -> super.filterMessage(m) + } + } + + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("EvenActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun watchingActors() { + val watched = object : Actor("WatchedActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatchedActor Starting") + receive(500, TimeUnit.MILLISECONDS) + LOG.info("WatchedActor Finishing") + return null + } + } + + val watcher = object : Actor("WatcherActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatcherActor Listening") + try { + LOG.info("WatcherActor received Message: {}", receive(2, TimeUnit.SECONDS)) + } catch (e: Exception) { + LOG.info("WatcherActor Received Exception", e) + } + return null + } + + @Suspendable + override fun handleLifecycleMessage(m: LifecycleMessage?): Int? { + LOG.info("WatcherActor Received Lifecycle Message: {}", m) + return super.handleLifecycleMessage(m) + } + } + + val watcherRef = watcher.spawn() + TimeUnit.MILLISECONDS.sleep(200) + + val watchedRef = watched.spawn() + watcher.link(watchedRef) + + watched.join() + watcher.join() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt new file mode 100644 index 0000000000..83e06bf7d6 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt @@ -0,0 +1,135 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.channels.Channels +import co.paralleluniverse.strands.channels.Topic +import co.paralleluniverse.strands.channels.reactivestreams.ReactiveStreams +import org.junit.Test +import org.reactivestreams.Subscriber +import org.reactivestreams.Subscription +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ReactiveStreamsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ReactiveStreamsTest::class.java) + } + + @Test + fun publisher() { + val inputChannel = Channels.newChannel(1); + + val publisher = ReactiveStreams.toPublisher(inputChannel) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError: {}", t) + } + }) + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } + + @Test + fun publisherTopic() { + val inputTopic = Topic() + + val publisher = ReactiveStreams.toPublisher(inputTopic) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 1") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 1: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 1: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 1: {}", t) + } + }) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 2") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 2: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 2: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 2: {}", t) + } + }) + + inputTopic.send("Hello") + inputTopic.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputTopic.close() + } + + @Test + fun subscribe() { + val inputChannel = Channels.newChannel(10); + val publisher = ReactiveStreams.toPublisher(inputChannel) + + val channel = ReactiveStreams.subscribe(10, Channels.OverflowPolicy.THROW, publisher) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + LOG.info("Received: {}", message) + } + LOG.info("Stopped receiving messages") + } + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } +} diff --git a/libraries-2/README.md b/libraries-2/README.md index cdeed10b3f..1b042ac3c5 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -5,3 +5,6 @@ - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) +- [Templating with Handlebars](https://www.baeldung.com/handlebars) +- [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 7bd3f5b355..ff73888b69 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -5,11 +5,13 @@ 4.0.0 libraries2 libraries2 + com.baeldung parent-modules 1.0.0-SNAPSHOT + jboss-public-repository-group @@ -25,6 +27,7 @@ + org.mapdb @@ -34,7 +37,7 @@ com.pivovarit parallel-collectors - 1.1.0 + ${parallel-collectors.version} org.assertj @@ -96,22 +99,22 @@ com.squareup.okhttp3 okhttp - 3.14.2 + ${okhttp.version} com.fasterxml.jackson.core jackson-databind - 2.9.9 + ${jackson.version} com.google.code.gson gson - 2.8.5 + ${gson.version} com.squareup.okhttp3 mockwebserver - 3.14.2 + ${mockwebserver.version} test @@ -122,7 +125,7 @@ com.github.jknack handlebars - 4.1.2 + ${handlebars.version} @@ -141,6 +144,7 @@ ${mesos.library.version} + 3.0.7 3.6.2 @@ -156,5 +160,10 @@ 0.6.0 1.19 0.28.3 + 1.1.0 + 3.14.2 + 2.8.5 + 3.14.2 + 4.1.2 diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml index cb5990df22..05d11d83fe 100644 --- a/libraries-apache-commons/pom.xml +++ b/libraries-apache-commons/pom.xml @@ -25,7 +25,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} org.apache.commons @@ -35,7 +35,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} commons-chain @@ -87,13 +87,12 @@ - 3.6 + 3.6 1.1 1.9.3 1.2 1.4 3.6.2 - 2.5 1.6 4.1 2.0.0.0 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 31aaaea951..88dcceafaa 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -449,7 +449,6 @@ 2.8.2 1.1.0 1.5.0 - 2.9.7 3.0.0 3.6.2 3.8.4 diff --git a/libraries-http/README.md b/libraries-http/README.md new file mode 100644 index 0000000000..dd8c6a5f67 --- /dev/null +++ b/libraries-http/README.md @@ -0,0 +1,7 @@ + +### Relevant Articles: + +- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) +- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client) +- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) +- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml new file mode 100644 index 0000000000..6006a93aef --- /dev/null +++ b/libraries-http/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + libraries-http + libraries-http + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + com.google.http-client + google-http-client + ${googleclient.version} + + + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} + + + com.google.http-client + google-http-client-gson + ${googleclient.version} + + + + + org.asynchttpclient + async-http-client + ${async.http.client.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + com.google.code.gson + gson + 2.8.5 + + + + com.squareup.okhttp3 + mockwebserver + ${com.squareup.okhttp3.version} + test + + + + + + 3.6.2 + 3.14.2 + 1.23.0 + 2.2.0 + + diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties diff --git a/rest-with-spark-java/src/main/resources/logback.xml b/libraries-http/src/main/resources/logback.xml similarity index 100% rename from rest-with-spark-java/src/main/resources/logback.xml rename to libraries-http/src/main/resources/logback.xml diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java b/libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java rename to libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/client/Consts.java b/libraries-http/src/test/java/com/baeldung/client/Consts.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/client/Consts.java rename to libraries-http/src/test/java/com/baeldung/client/Consts.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java b/libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java rename to libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 75980a5360..7b28c17607 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -19,6 +19,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java index 3edd2eab06..5efc4aa998 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java @@ -17,6 +17,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 95% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java index 207ad14e71..24617794d1 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -20,6 +20,9 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 94% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java index 66fee0b626..19e689c093 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -20,6 +20,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java b/libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java rename to libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java diff --git a/libraries-io/README.md b/libraries-io/README.md new file mode 100644 index 0000000000..90095a2f23 --- /dev/null +++ b/libraries-io/README.md @@ -0,0 +1,5 @@ + +### Relevant Articles: + +- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) + diff --git a/libraries-io/pom.xml b/libraries-io/pom.xml new file mode 100644 index 0000000000..5b78ae9442 --- /dev/null +++ b/libraries-io/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + libraries-io + libraries-io + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.jcraft + jsch + ${jsch.version} + + + com.hierynomus + sshj + ${sshj.version} + + + org.apache.commons + commons-vfs2 + ${vfs.version} + + + + + + 0.1.55 + 0.27.0 + 2.4 + + diff --git a/libraries-io/src/main/resources/input.txt b/libraries-io/src/main/resources/input.txt new file mode 100644 index 0000000000..a10db923e5 --- /dev/null +++ b/libraries-io/src/main/resources/input.txt @@ -0,0 +1 @@ +This is a sample text content \ No newline at end of file diff --git a/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java new file mode 100644 index 0000000000..192153bc90 --- /dev/null +++ b/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java @@ -0,0 +1,106 @@ +package org.baeldung.java.io.remote; + +import java.io.IOException; + +import org.apache.commons.vfs2.FileObject; +import org.apache.commons.vfs2.FileSystemManager; +import org.apache.commons.vfs2.Selectors; +import org.apache.commons.vfs2.VFS; +import org.junit.Test; + +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpException; + +import net.schmizz.sshj.SSHClient; +import net.schmizz.sshj.sftp.SFTPClient; +import net.schmizz.sshj.transport.verification.PromiscuousVerifier; + +public class SftpFileTransferLiveTest { + + private String remoteHost = "HOST_NAME_HERE"; + private String username = "USERNAME_HERE"; + private String password = "PASSWORD_HERE"; + private String localFile = "src/main/resources/input.txt"; + private String remoteFile = "welcome.txt"; + private String localDir = "src/main/resources/"; + private String remoteDir = "remote_sftp_test/"; + private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample"; + + @Test + public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.put(localFile, remoteDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.get(remoteFile, localDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenUploadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.put(localFile, remoteDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenDownloadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.get(remoteFile, localDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt"); + remote.copyFrom(local, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + @Test + public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt"); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile); + local.copyFrom(remote, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + // ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample + + private ChannelSftp setupJsch() throws JSchException { + JSch jsch = new JSch(); + jsch.setKnownHosts(knownHostsFileLoc); + Session jschSession = jsch.getSession(username, remoteHost); + jschSession.setPassword(password); + //jschSession.setConfig("StrictHostKeyChecking", "no"); + jschSession.connect(); + return (ChannelSftp) jschSession.openChannel("sftp"); + } + + private SSHClient setupSshj() throws IOException { + SSHClient client = new SSHClient(); + client.addHostKeyVerifier(new PromiscuousVerifier()); + client.connect(remoteHost); + client.authPassword(username, password); + return client; + } + +} diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 72794729a5..9bed5e211b 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -52,7 +52,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} io.netty @@ -114,7 +114,6 @@ 3.6.2 4.5.3 - 2.5 9.4.8.v20171121 4.1.20.Final 4.1 diff --git a/libraries/README.md b/libraries/README.md index f6a39daef1..c7b40e3c94 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -36,16 +36,12 @@ - [Introduction To Docx4J](http://www.baeldung.com/docx4j) - [Introduction to StreamEx](http://www.baeldung.com/streamex) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) -- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) - [Introduction to Smooks](http://www.baeldung.com/smooks) -- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) -- [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) diff --git a/libraries/pom.xml b/libraries/pom.xml index 886dd3c4a2..e8ffde5f99 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -18,23 +18,12 @@ akka-actor_2.12 ${typesafe-akka.version} - - - - com.typesafe.akka akka-testkit_2.12 ${typesafe-akka.version} test - - - - org.asynchttpclient - async-http-client - ${async.http.client.version} - org.beykery @@ -56,7 +45,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} commons-net @@ -829,7 +818,6 @@ 0.1.0 0.7.0 3.2.7 - 3.6 1.9.2 1.2 3.21.0-GA @@ -837,12 +825,10 @@ 1.5.0 3.1.0 4.5.3 - 1.4.196 1.0 4.5.3 - 2.9.7 2.92 1.9.26 1.41.0 @@ -875,7 +861,6 @@ 2.0.0 1.7.0 3.0.14 - 2.2.0 9.1.5.Final 4.1 1.4.9 diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index ae658e034e..ce58f43e4e 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -101,7 +101,6 @@ 2.7 3.3.6 3.3.0.Final - 2.4 diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java index 5ac82a74d8..604c45be3b 100644 --- a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java @@ -13,9 +13,9 @@ public class GetterLazy { private static final String DELIMETER = ","; @Getter(lazy = true) - private final Map transactions = readTxnsFromFile(); + private final Map transactions = getTransactions(); - private Map readTxnsFromFile() { + private Map getTransactions() { final Map cache = new HashMap<>(); List txnRows = readTxnListFromFile(); diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java new file mode 100644 index 0000000000..07198d2ffc --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java @@ -0,0 +1,26 @@ +package com.baeldung.lombok.intro; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +import lombok.SneakyThrows; +import lombok.Synchronized; + +public class Utility { + + @SneakyThrows + public String resourceAsString() throws IOException { + try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + return br.lines().collect(Collectors.joining("\n")); + } + } + + @Synchronized + public void putValueInCache(String key, String value) { + System.out.println("Thread safe here with key : [" + key + "] and value[" + value + "]"); + } +} diff --git a/lombok/src/main/resources/sure_in_my_jar.txt b/lombok/src/main/resources/sure_in_my_jar.txt new file mode 100644 index 0000000000..5ab2f8a432 --- /dev/null +++ b/lombok/src/main/resources/sure_in_my_jar.txt @@ -0,0 +1 @@ +Hello \ No newline at end of file diff --git a/maven-java-11/multimodule-maven-project/daomodule/pom.xml b/maven-java-11/multimodule-maven-project/daomodule/pom.xml index de9be656d4..5520c5a90a 100644 --- a/maven-java-11/multimodule-maven-project/daomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/daomodule/pom.xml @@ -1,14 +1,15 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.daomodule daomodule jar 1.0 daomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml index 8e700e62b5..747722e912 100644 --- a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.entitymodule entitymodule jar 1.0 entitymodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + 11 11 diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml index d2c94527f1..3e5ec122ff 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml @@ -1,16 +1,17 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.mainappmodule mainappmodule 1.0 jar mainappmodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml index f22541738c..7e2eb0dd7b 100644 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ b/maven-java-11/multimodule-maven-project/pom.xml @@ -6,12 +6,20 @@ 1.0 pom multimodule-maven-project + com.baeldung.maven-java-11 maven-java-11 1.0 + + entitymodule + daomodule + userdaomodule + mainappmodule + + @@ -45,13 +53,6 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index b4fe7f0398..68e7ae9b82 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.userdaomodule userdaomodule 1.0 jar userdaomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + com.baeldung.entitymodule diff --git a/maven-java-11/pom.xml b/maven-java-11/pom.xml index ff95840523..5ae4c00892 100644 --- a/maven-java-11/pom.xml +++ b/maven-java-11/pom.xml @@ -6,14 +6,17 @@ 1.0 pom maven-java-11 + - parent-modules - com.baeldung - 1.0.0-SNAPSHOT + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + multimodule-maven-project + UTF-8 11 diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-polyglot/maven-polyglot-json-app/pom.json index abd58f3127..3e809b7b83 100644 --- a/maven-polyglot/maven-polyglot-json-app/pom.json +++ b/maven-polyglot/maven-polyglot-json-app/pom.json @@ -5,10 +5,10 @@ "version": "1.0-SNAPSHOT", "name": "Json Maven Polyglot", "parent": { - "groupId": "org.springframework.boot", - "artifactId": "spring-boot-starter-parent", - "version": "2.0.5.RELEASE", - "relativePath": null + "groupId": "com.baeldung", + "artifactId": "parent-boot-2", + "version": "0.0.1-SNAPSHOT", + "relativePath": "../../parent-boot-2" }, "properties": { "project.build.sourceEncoding": "UTF-8", diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 5b18529ec5..1170fe7aa6 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -8,17 +8,24 @@ 1.0-SNAPSHOT maven-polyglot-json-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + org.apache.maven maven-core - 3.5.4 + ${maven-core.version} provided com.fasterxml.jackson.core jackson-databind - 2.9.6 + ${jackson.version} @@ -42,6 +49,7 @@ 1.8 1.8 + 3.5.4 \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/pom.yml b/maven-polyglot/maven-polyglot-yml-app/pom.yml index 445e2eec3b..393f7e9e15 100644 --- a/maven-polyglot/maven-polyglot-yml-app/pom.yml +++ b/maven-polyglot/maven-polyglot-yml-app/pom.yml @@ -4,4 +4,10 @@ artifactId: maven-polyglot-yml-app version: 1.0-SNAPSHOT name: 'YAML Demo' +parent: + groupId: "com.baeldung" + artifactId: "parent-modules" + version: "1.0.0-SNAPSHOT" + relativePath: "../.." + properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8} \ No newline at end of file diff --git a/maven/pom.xml b/maven/pom.xml index 942bf683e2..ef6e7b7d93 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -4,12 +4,19 @@ com.baeldung maven 0.0.1-SNAPSHOT + maven + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + custom-rule maven-enforcer - maven - pom @@ -292,7 +299,6 @@ - 1.8 3.0.2 3.8.0 2.22.0 @@ -303,6 +309,5 @@ Baeldung 9.4.11.v20180605 2.27 - 4.12 \ No newline at end of file diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml index 7608e4d168..df8ee9a20e 100644 --- a/maven/versions-maven-plugin/original/pom.xml +++ b/maven/versions-maven-plugin/original/pom.xml @@ -11,19 +11,19 @@ commons-io commons-io - 2.3 + ${commons-io.version} org.apache.commons commons-collections4 - 4.0 + ${commons-collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons-lang3.version} @@ -35,7 +35,7 @@ commons-beanutils commons-beanutils - 1.9.1-SNAPSHOT + ${commons-beanutils.version} @@ -71,6 +71,10 @@ 1.15 + 2.3 + 4.0 + 3.0 + 1.9.1 \ No newline at end of file diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml index dc0cba75f9..e0714bf0e0 100644 --- a/maven/versions-maven-plugin/pom.xml +++ b/maven/versions-maven-plugin/pom.xml @@ -6,10 +6,6 @@ versions-maven-plugin 0.0.1-SNAPSHOT versions-maven-plugin - - - 1.15 - @@ -73,5 +69,9 @@ + + + 1.15 + \ No newline at end of file diff --git a/msf4j/pom.xml b/msf4j/pom.xml index 4a6f63159d..2a862ac289 100644 --- a/msf4j/pom.xml +++ b/msf4j/pom.xml @@ -23,6 +23,7 @@ + org.wso2.msf4j diff --git a/oauth2-framework-impl/oauth2-authorization-server/pom.xml b/oauth2-framework-impl/oauth2-authorization-server/pom.xml new file mode 100644 index 0000000000..8db2150558 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + oauth2-authorization-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 1.4.199 + 9080 + 9443 + + + + + com.nimbusds + nimbus-jose-jwt + 7.3 + + + org.bouncycastle + bcprov-jdk15on + 1.62 + + + org.bouncycastle + bcpkix-jdk15on + 1.62 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-h2-dependency + package + + copy + + + + + + + com.h2database + h2 + ${h2.version} + jar + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java new file mode 100644 index 0000000000..62d6b04464 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class OAuth2ServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java new file mode 100644 index 0000000000..dab57b91a7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java @@ -0,0 +1,17 @@ +package com.baeldung.oauth2.authorization.server; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static java.lang.Thread.currentThread; + + +public class PEMKeyUtils { + + public static String readKeyAsString(String keyLocation) throws Exception { + URI uri = currentThread().getContextClassLoader().getResource(keyLocation).toURI(); + byte[] byteArray = Files.readAllBytes(Paths.get(uri)); + return new String(byteArray); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java new file mode 100644 index 0000000000..10e78a2dfd --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java @@ -0,0 +1,185 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.annotation.security.RolesAllowed; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import java.io.IOException; +import java.net.URI; +import java.security.Principal; +import java.time.LocalDateTime; +import java.util.*; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue(loginPage = "/login.jsp", errorPage = "/login.jsp") +) +@RolesAllowed("USER") +@RequestScoped +@Path("authorize") +public class AuthorizationEndpoint { + + @Inject + private SecurityContext securityContext; + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @GET + @Produces(MediaType.TEXT_HTML) + public Response doGet(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @Context UriInfo uriInfo) throws ServletException, IOException { + MultivaluedMap params = uriInfo.getQueryParameters(); + Principal principal = securityContext.getCallerPrincipal(); + + //error about redirect_uri && client_id ==> forward user, thus to error.jsp. + //otherwise ==> sendRedirect redirect_uri?error=error&error_description=error_description + //1. client_id + String clientId = params.getFirst("client_id"); + if (clientId == null || clientId.isEmpty()) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + Client client = appDataRepository.getClient(clientId); + if (client == null) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + //2. Client Authorized Grant Type + String clientError = ""; + if (client.getAuthorizedGrantTypes() != null && !client.getAuthorizedGrantTypes().contains("authorization_code")) { + return informUserAboutError(request, response, "Authorization Grant type, authorization_code, is not allowed for this client :" + clientId); + } + + //3. redirectUri + String redirectUri = params.getFirst("redirect_uri"); + if (client.getRedirectUri() != null && !client.getRedirectUri().isEmpty()) { + if (redirectUri != null && !redirectUri.isEmpty() && !client.getRedirectUri().equals(redirectUri)) { + //sould be in the client.redirectUri + return informUserAboutError(request, response, "redirect_uri is pre-registred and should match"); + } + redirectUri = client.getRedirectUri(); + params.putSingle("resolved_redirect_uri", redirectUri); + } else { + if (redirectUri == null || redirectUri.isEmpty()) { + return informUserAboutError(request, response, "redirect_uri is not pre-registred and should be provided"); + } + params.putSingle("resolved_redirect_uri", redirectUri); + } + request.setAttribute("client", client); + + //4. response_type + String responseType = params.getFirst("response_type"); + if (!"code".equals(responseType) && !"token".equals(responseType)) { + //error = "invalid_grant :" + responseType + ", response_type params should be code or token:"; + //return informUserAboutError(error); + } + + //Save params in session + request.getSession().setAttribute("ORIGINAL_PARAMS", params); + + //4.scope: Optional + String requestedScope = request.getParameter("scope"); + if (requestedScope == null || requestedScope.isEmpty()) { + requestedScope = client.getScope(); + } + User user = appDataRepository.getUser(principal.getName()); + String allowedScopes = checkUserScopes(user.getScopes(), requestedScope); + request.setAttribute("scopes", allowedScopes); + + request.getRequestDispatcher("/authorize.jsp").forward(request, response); + return null; + } + + @POST + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Produces(MediaType.TEXT_HTML) + public Response doPost(@Context HttpServletRequest request, + @Context HttpServletResponse response, + MultivaluedMap params) throws Exception { + MultivaluedMap originalParams = (MultivaluedMap) request.getSession().getAttribute("ORIGINAL_PARAMS"); + if (originalParams == null) { + return informUserAboutError(request, response, "No pending authorization request."); + } + String redirectUri = originalParams.getFirst("resolved_redirect_uri"); + StringBuilder sb = new StringBuilder(redirectUri); + + String approbationStatus = params.getFirst("approbation_status"); + if ("NO".equals(approbationStatus)) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + //==> YES + List approvedScopes = params.get("scope"); + if (approvedScopes == null || approvedScopes.isEmpty()) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + + String responseType = originalParams.getFirst("response_type"); + String clientId = originalParams.getFirst("client_id"); + if ("code".equals(responseType)) { + String userId = securityContext.getCallerPrincipal().getName(); + AuthorizationCode authorizationCode = new AuthorizationCode(); + authorizationCode.setClientId(clientId); + authorizationCode.setUserId(userId); + authorizationCode.setApprovedScopes(String.join(" ", approvedScopes)); + authorizationCode.setExpirationDate(LocalDateTime.now().plusMinutes(10)); + authorizationCode.setRedirectUri(redirectUri); + appDataRepository.save(authorizationCode); + String code = authorizationCode.getCode(); + sb.append("?code=").append(code); + } else { + //Implicit: responseType=token + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of("implicit")).get(); + JsonObject tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + sb.append("#access_token=").append(tokenResponse.getString("access_token")) + .append("&token_type=").append(tokenResponse.getString("token_type")) + .append("&scope=").append(tokenResponse.getString("scope")); + } + String state = originalParams.getFirst("state"); + if (state != null) { + sb.append("&state=").append(state); + } + return Response.seeOther(UriBuilder.fromUri(sb.toString()).build()).build(); + } + + private String checkUserScopes(String userScopes, String requestedScope) { + Set allowedScopes = new LinkedHashSet<>(); + Set rScopes = new HashSet(Arrays.asList(requestedScope.split(" "))); + Set uScopes = new HashSet(Arrays.asList(userScopes.split(" "))); + for (String scope : uScopes) { + if (rScopes.contains(scope)) allowedScopes.add(scope); + } + return String.join(" ", allowedScopes); + } + + private Response informUserAboutError(HttpServletRequest request, HttpServletResponse response, String error) throws ServletException, IOException { + request.setAttribute("error", error); + request.getRequestDispatcher("/error.jsp").forward(request, response); + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java new file mode 100644 index 0000000000..9d38c823b9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.jwk.JWK; +import org.eclipse.microprofile.config.Config; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; + +@Path("jwk") +@ApplicationScoped +public class JWKEndpoint { + + @Inject + private Config config; + + @GET + public Response getKey(@QueryParam("format") String format) throws Exception { + if (format != null && !Arrays.asList("jwk", "pem").contains(format)) { + return Response.status(Response.Status.BAD_REQUEST).entity("Public Key Format should be : jwk or pem").build(); + } + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + if (format == null || format.equals("jwk")) { + JWK jwk = JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return Response.ok(jwk.toJSONString()).type(MediaType.APPLICATION_JSON).build(); + } else if (format.equals("pem")) { + return Response.ok(pemEncodedRSAPublicKey).build(); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java new file mode 100644 index 0000000000..f39bb2ea2d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -0,0 +1,86 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.nimbusds.jose.JOSEException; + +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.*; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@Path("token") +public class TokenEndpoint { + + List supportedGrantTypes = Collections.singletonList("authorization_code"); + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public Response token(MultivaluedMap params, + @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) throws JOSEException { + + //Check grant_type params + String grantType = params.getFirst("grant_type"); + Objects.requireNonNull(grantType, "grant_type params is required"); + if (!supportedGrantTypes.contains(grantType)) { + JsonObject error = Json.createObjectBuilder() + .add("error", "unsupported_grant_type") + .add("error_description", "grant type should be one of :" + supportedGrantTypes) + .build(); + return Response.status(Response.Status.BAD_REQUEST) + .entity(error).build(); + + } + + //Client Authentication + String[] clientCredentials = extract(authHeader); + String clientId = clientCredentials[0]; + String clientSecret = clientCredentials[1]; + Client client = appDataRepository.getClient(clientId); + if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) { + JsonObject error = Json.createObjectBuilder() + .add("error", "invalid_client") + .build(); + return Response.status(Response.Status.UNAUTHORIZED) + .entity(error).build(); + } + + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); + JsonObject tokenResponse = null; + try { + tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (Exception e) { + e.printStackTrace(); + } + + return Response.ok(tokenResponse) + .header("Cache-Control", "no-store") + .header("Pragma", "no-cache") + .build(); + } + + private String[] extract(String authHeader) { + if (authHeader != null && authHeader.startsWith("Basic ")) { + return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java new file mode 100644 index 0000000000..889c7fcea2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java @@ -0,0 +1,99 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +@Named("authorization_code") +public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler { + + @PersistenceContext + private EntityManager entityManager; + + @Inject + private Config config; + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + //1. code is required + String code = params.getFirst("code"); + if (code == null || "".equals(code)) { + throw new WebApplicationException("invalid_grant"); + } + AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code); + if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) { + throw new WebApplicationException("code Expired !"); + } + String redirectUri = params.getFirst("redirect_uri"); + //redirecturi match + if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) { + //redirectUri params should be the same as the requested redirectUri. + throw new WebApplicationException("invalid_grant"); + } + //client match + if (!clientId.equals(authorizationCode.getClientId())) { + throw new WebApplicationException("invalid_grant"); + } + + //JWT Header + JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + Instant now = Instant.now(); + Long expiresInMin = 30L; + Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(authorizationCode.getUserId()) + .claim("upn", authorizationCode.getUserId()) + .audience("http://localhost:9280") + .claim("scope", authorizationCode.getApprovedScopes()) + .claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" "))) + .expirationTime(expiresIn) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + + //4. Signing + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey())); + + //5. Finally the JWT access token + String accessToken = signedJWT.serialize(); + + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", authorizationCode.getApprovedScopes()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java new file mode 100644 index 0000000000..a5afe293ef --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import javax.json.JsonObject; +import javax.ws.rs.core.MultivaluedMap; + +public interface AuthorizationGrantTypeHandler { + JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception; +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java new file mode 100644 index 0000000000..6b827d6a3d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +@ApplicationScoped +public class AppDataRepository { + + @PersistenceContext + private EntityManager entityManager; + + public Client getClient(String clientId) { + return entityManager.find(Client.class, clientId); + } + + public User getUser(String userId) { + return entityManager.find(User.class, userId); + } + + @Transactional + public AuthorizationCode save(AuthorizationCode authorizationCode) { + entityManager.persist(authorizationCode); + return authorizationCode; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java new file mode 100644 index 0000000000..a2ec088eb9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java @@ -0,0 +1,73 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Entity +@Table(name = "authorization_code") +public class AuthorizationCode { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "code") + private String code; + @Column(name = "client_id") + private String clientId; + @Column(name = "user_id") + private String userId; + @Column(name = "approved_scopes") + private String approvedScopes; + + @Column(name = "redirect_uri") + private String redirectUri; + + @Column(name = "expiration_date") + private LocalDateTime expirationDate; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getApprovedScopes() { + return approvedScopes; + } + + public void setApprovedScopes(String approvedScopes) { + this.approvedScopes = approvedScopes; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public LocalDateTime getExpirationDate() { + return expirationDate; + } + + public void setExpirationDate(LocalDateTime expirationDate) { + this.expirationDate = expirationDate; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java new file mode 100644 index 0000000000..9b5ad2f904 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java @@ -0,0 +1,62 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "clients") +public class Client { + @Id + @Column(name = "client_id") + private String clientId; + @Column(name = "client_secret") + private String clientSecret; + @Column(name = "redirect_uri") + private String redirectUri; + @Column(name = "scope") + private String scope; + @Column(name = "authorized_grant_types") + private String authorizedGrantTypes; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getAuthorizedGrantTypes() { + return authorizedGrantTypes; + } + + public void setAuthorizedGrantTypes(String authorizedGrantTypes) { + this.authorizedGrantTypes = authorizedGrantTypes; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java new file mode 100644 index 0000000000..b3821715f4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java @@ -0,0 +1,58 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.security.Principal; + +@Entity +@Table(name = "users") +public class User implements Principal { + @Id + @Column(name = "user_id") + private String userId; + @Column(name = "password") + private String password; + @Column(name = "roles") + private String roles; + @Column(name = "scopes") + private String scopes; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getScopes() { + return scopes; + } + + public void setScopes(String scopes) { + this.scopes = scopes; + } + + @Override + public String getName() { + return getUserId(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java new file mode 100644 index 0000000000..a32ab32cd4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java @@ -0,0 +1,37 @@ +package com.baeldung.oauth2.authorization.server.security; + +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import javax.transaction.Transactional; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +@Transactional +public class UserIdentityStore implements IdentityStore { + + @Inject + private AppDataRepository appDataRepository; + + @Override + public CredentialValidationResult validate(Credential credential) { + UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential; + String userId = usernamePasswordCredential.getCaller(); + User user = appDataRepository.getUser(userId); + Objects.requireNonNull(user, "User should be not null"); + if (usernamePasswordCredential.getPasswordAsString().equals(user.getPassword())) { + return new CredentialValidationResult(userId, new HashSet<>(Arrays.asList(user.getRoles().split(",")))); + } + return INVALID_RESULT; + } +} \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java new file mode 100644 index 0000000000..84b9a89c54 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java @@ -0,0 +1,209 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationCode; +//import Client; +//import User; +//import com.baeldung.security.oauth2.server.service.AuthCodeService; +// +//import javax.ejb.EJB; +//import javax.enterprise.context.RequestScoped; +//import javax.inject.Inject; +//import javax.persistence.EntityManager; +//import javax.persistence.PersistenceContext; +//import javax.security.enterprise.SecurityContext; +//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +//import javax.servlet.ServletException; +//import javax.servlet.annotation.HttpConstraint; +//import javax.servlet.annotation.ServletSecurity; +//import javax.servlet.annotation.WebServlet; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.IOException; +//import java.security.Principal; +//import java.util.*; +// +///** +// * 1. GET http://localhost:8080/app/ (302) +// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input +// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302) +// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200) +// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200) +// */ +///* +// +//Query Params: +// client_id: app +// redirect_uri: http://localhost:8080/app/ +// response_type: code +// state: A123 +// +// ==> GET user login WITH client request as hidden input: +// +// +// ==> After user login ==> Initial client request +// ==> gen code +// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123 +//*/ +// +////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 +////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123 +// +////@RequestScoped +//@FormAuthenticationMechanismDefinition( +// loginToContinue = @LoginToContinue( +// loginPage = "/login-servlet", +// errorPage = "/login-error-servlet" +// ) +//) +//@WebServlet({"/authorize"}) +//@ServletSecurity(@HttpConstraint(rolesAllowed = "user")) +////@Stateless +//@RequestScoped +//public class AuthorizationEndpoint extends HttpServlet { +// +// private static final List authorizedResponseTypes = Arrays.asList("code", "token"); +// +// @Inject +// private SecurityContext securityContext; +// +// @PersistenceContext(name = "jpa-oauth2-pu") +// private EntityManager entityManager; +// +// @EJB +// private AuthCodeService authCodeService; +// +// //HTTP GET IS A MUST, POST IS OPTIONAL +// @Override +// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// +// String error = ""; +// +// //1. User Authentication +// Principal principal = securityContext.getCallerPrincipal(); +// +// //2. Check for a valid client_id +// String clientId = request.getParameter("client_id"); +// if (clientId == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// request.setAttribute("clientId", clientId); +// Client client = entityManager.find(Client.class, clientId); +// if (client == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// +// //3. check for a valid response_type +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// request.getRequestDispatcher("/error.jsp") +// .forward(request, response); +// } +// +// //4. Optional redirect_uri, if provided should match +// String redirectUri = request.getParameter("redirect_uri"); +// checkRedirectUri(client, redirectUri); +// +// //save params +// String currentUri = request.getRequestURI(); +// request.setAttribute("post_redirect_uri", currentUri); +// +// String state = request.getParameter("state"); +// Map requestMap = new HashMap<>(); +// requestMap.put("response_type", responseType); +// requestMap.put("client_id", clientId); +// requestMap.put("redirect_uri", redirectUri); +// requestMap.put("state", state); +// request.setAttribute("requestMap", requestMap); +// +// //5.scope: Optional +// String requestedScope = request.getParameter("scope"); +// if (requestedScope.isEmpty()) { +// requestedScope = client.getScope(); +// } +// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes) +// //checkRequestedScope(requestedScope, client.getScope()); +// +// //sub set of user scope +// //allowed scope by the user +// +// User user = entityManager.find(User.class, principal.getName()); +// request.setAttribute("scopes", requestedScope); +// +// +// forward("/authorize.jsp", request, response); +// } +// +// @Override +// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// String clientId = request.getParameter("client_id"); +// +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// forward("/error.jsp", request, response); +// } +// +// Client client = entityManager.find(Client.class, clientId); +// Objects.requireNonNull(client); +// +// String userId = securityContext.getCallerPrincipal().getName(); +// AuthorizationCode authorizationCode = new AuthorizationCode(); +// authorizationCode.setClientId(clientId); +// authorizationCode.setUserId(userId); +// String redirectUri = request.getParameter("redirect_uri"); +// authorizationCode.setRedirectUri(redirectUri); +// +// redirectUri = checkRedirectUri(client, redirectUri); +// +// String[] scope = request.getParameterValues("scope"); +// if (scope == null) { +// request.setAttribute("error", "User doesn't approved any scope"); +// forward("/error.jsp", request, response); +// } +// +// String approvedScopes = String.join(" ", scope); +// authorizationCode.setApprovedScopes(approvedScopes); +// +// //entityManager.persist(authorizationCode); +// authCodeService.save(authorizationCode); +// String code = authorizationCode.getCode(); +// +// StringBuilder sb = new StringBuilder(redirectUri); +// sb.append("?code=").append(code); +// +// //If the client send a state, Send it back +// String state = request.getParameter("state"); +// if (state != null) { +// sb.append("&state=").append(state); +// } +// response.sendRedirect(sb.toString()); +// } +// +// private String checkRedirectUri(Client client, String redirectUri) { +// //redirect uri +// if (redirectUri == null) { +// //erreur: param redirect_uri && client redirect_uri don't match. +// redirectUri = client.getRedirectUri(); +// if (redirectUri == null) { +// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri."); +// } +// } else if (!redirectUri.equals(client.getRedirectUri())) { +// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match."); +// } +// return redirectUri; +// } +// +// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// request.getRequestDispatcher(path) +// .forward(request, response); +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java new file mode 100644 index 0000000000..73085a68d1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java @@ -0,0 +1,70 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationGrantTypeHandler; +//import TokenResponse; +//import com.baeldung.security.oauth2.server.security.Authenticated; +//import com.nimbusds.jose.JOSEException; +// +//import javax.enterprise.inject.Instance; +//import javax.enterprise.inject.literal.NamedLiteral; +//import javax.inject.Inject; +//import javax.security.enterprise.SecurityContext; +//import javax.ws.rs.Consumes; +//import javax.ws.rs.POST; +//import javax.ws.rs.Path; +//import javax.ws.rs.Produces; +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.MultivaluedMap; +//import javax.ws.rs.core.Response; +//import java.security.Principal; +//import java.util.Arrays; +//import java.util.List; +//import java.util.Objects; +// +///** +// * { +// * "access_token" : "acb6803a48114d9fb4761e403c17f812", +// * "token_type" : "bearer", +// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ", +// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r", +// * "expires_in" : 43199, +// * "scope" : "openid oauth.approvals", +// * "jti" : "acb6803a48114d9fb4761e403c17f812" +// * } +// */ +//@Path("token") +//public class TokenEndpoint { +// +// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials"); +// +// @Inject +// private SecurityContext securityContext; +// +// @Inject +// Instance authorizationGrantTypeHandlers; +// +// @POST +// @Produces(MediaType.APPLICATION_JSON) +// @Consumes(MediaType.APPLICATION_FORM_URLENCODED) +// @Authenticated +// public Response token(MultivaluedMap params) throws JOSEException { +// //Authenticate client with [basic] http authentication mechanism +// Principal principal = securityContext.getCallerPrincipal(); +// Objects.requireNonNull(principal, "Client not authenticated!"); +// +// //Check grant_type params +// String grantType = params.getFirst("grant_type"); +// Objects.requireNonNull(grantType, "grant_type params is required"); +// //authorization_code, password, refresh, client_credentials +// if (!supportedGrantTypes.contains(grantType)) { +// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes); +// } +// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); +// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params); +// Response response = Response.ok(tokenResponse) +// .header("Cache-Control", "no-store") +// .header("Pragma", "no-cache") +// .build(); +// return response; +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..97d9ec4a28 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml @@ -0,0 +1,32 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jpa-2.2 + appSecurity-3.0 + jsp-2.3 + mpConfig-1.3 + + + + + + + + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d9c68bc111 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +signingkey=/META-INF/private-key.pem +verificationkey=/META-INF/public-key.pem diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..a10ad3c886 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + jdbc/OAuth2_DS + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem new file mode 100644 index 0000000000..6e36cb4d78 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYizUyvwY6qMd0 +ZkYPzP9mLTJOSczW8WtAbjhrgxk5LORIjcdv/aB1BAzDEOCX4UC+Rbs9YwaekIvW +7dL/t6xPzsA7+9tMt27TqUxXigWEFQG73w/WbEVzCG09IHqG7Ztjb6aGL+8pfcu+ +SLvOtXWrctHNbr35BYC5yBQaos9bH+nLYbh2Ff+emrpg7Kwoeis6MY6RgZIL/lxt +3beZt1NQhLEvB9t6XoSkyLQKSjT/OC8XOa4OYI4OfOSFqEUEp+8dKe3svZbQUNJf +KKehx78xx0rfwH+iBsFKkHdvt1ZHtINvYedAfGrc5rWnesunzOW7OKMAiIXAJSRA +rn9Iv5/fAgMBAAECggEAYHKwgSfAGIRwQhIDhqoh31qmG2SXjez9fjcZfhloNKUg +EIjFmcX3n+br4D42Kq+zbIwWd6MRobJz9oj6/9bJMsq9qHnnFWZmQHQZgqwBBPFu +UkVqAnE7BZ9tOFqs+EgAe+uQ2hejiHF1PA2dSNZd0L1VYRDAIJgo25aYDb0Sal0c +qaFmK1XzPnSIhgnopKP/TmUfALjeshtGvh6WkiXHTY2VKJlyLEiGd3/1tBZnzwSQ +QiS/2zfXL7lO0SYRA10m1BmtqGi3wSKIXUA6tNulmpXEMnYk4RtsqBClOanzQIm7 +f4Ie59AtUUlDdHzRmhxBaDprgAI/FdCxXkseLzk5sQKBgQDyptOhJ/VQ5tkgffJW +X2QwGIaNdvNCEL4GlgXKAWNkCzT4h+Q/2wFoKhaN2JH2YZwKCRwG/UZh4Hq22fdx +fa/DP8PK3zlX0c9dWQOtmBOe0/nG28kq9iqziP3ILLNuelfaMhxtRkUmR652VCzx +qazZmjoo2MxtA6BMiK3Vx5aikwKBgQDkdLalVveHKTVkrplQYNapQAtAwjlsNnMt +VJh6nLo3eOg1xBNA7JrYqx7sXRQInUGAyNKvgQL/lCQdMkTzyetLjJGsiFSEgeot +RMsDXBrJFYZiErbpQungpaevwAymaGi++nbCzhw1/n3AvVUhRKNknX8Ms0UKlLRZ +TCktCTChBQKBgGA7ZzzHgxPFqaCoMl6s0Cf+4gXigdDWoPYtszgM2uUHSMez5QKq +EWHFJ1Kz7BdBWMfmGvZupeYVR7WStf6NcRJHDJg9dRlt/QYxUjMbV9Sqjqmd6qce +H4s6LiOgDr0mygafzwRLVQs8bGVDNtvUhdd6wcwHRvOI957CqeZZlFT/AoGBAN2P +j79EW6U6wuyVJF0+vZDBauhwNQ6MtCEnZQWs0DCSUuop8d5KWVZ+huwGzTIZiPhk +S2goP4cs3eVu5k5k6oyHlJP2V7l24WzrxdPJVLTl6kFdEwWgfn//SGR7ZglRQxzM +fbcp+1QmL0FonZI5JhmjYR8pEXFUjJ/57AkgW4gdAoGASV3TlaNd+reb2l0kETqp +HrzzMIYkM2faZ8LmpcEO0wz606SK468bnl6SqVBYT2J0bkqCpEmPBtWs/OFCWd6x +93NndSfJk57/7AqNxfVyZWp2sjRzt5vZ4KPlRVvMHIGeJNbIV7RqUr6XGu+u3ZrS +B7SqwKZqdHVSULG9nMK7Iz8= +-----END PRIVATE KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql new file mode 100644 index 0000000000..ecda0fa2ad --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO `users` (`user_id`, `password`, `roles`, `scopes`) VALUES ('appuser', 'appusersecret', 'USER', 'resource.read resource.write'); + +INSERT INTO `clients` (`client_id`, `client_secret`, `redirect_uri`,`scope`,`authorized_grant_types`) VALUES ('webappclient', 'webappclientsecret', 'http://localhost:9180/callback', 'resource.read resource.write', 'authorization_code refresh_token'); \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp new file mode 100644 index 0000000000..1004b5b8b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -0,0 +1,54 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + Authorization + + + + +
+

Want to Authorize scopes for client : ${client.clientId} ?

+
+ +
+ + + + + + + + + +
Scopes : + + ${scope}
+
+
+ + +
+
+ +
+ + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp new file mode 100644 index 0000000000..edb0bf28b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + + Error + + + + + + +
+

${error}

+
+ + + \ No newline at end of file diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp similarity index 100% rename from spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt rename to oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp new file mode 100644 index 0000000000..1d2dd93fd0 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp @@ -0,0 +1,49 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + Login Form + + + + +
+

Login Form

+
+
+ + + + + + + + + + + + + +
Username
Password
+
+ +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/pom.xml b/oauth2-framework-impl/oauth2-client/pom.xml new file mode 100644 index 0000000000..e46a44268e --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + oauth2-client + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9180 + 9543 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java new file mode 100644 index 0000000000..a5fdaf07f2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java @@ -0,0 +1,39 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.UUID; + +@WebServlet(urlPatterns = "/authorize") +public class AuthorizationCodeServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //... + request.getSession().removeAttribute("tokenResponse"); + String state = UUID.randomUUID().toString(); + request.getSession().setAttribute("CLIENT_LOCAL_STATE", state); + + String authorizationUri = config.getValue("provider.authorizationUri", String.class); + String clientId = config.getValue("client.clientId", String.class); + String redirectUri = config.getValue("client.redirectUri", String.class); + String scope = config.getValue("client.scope", String.class); + + String authorizationLocation = authorizationUri + "?response_type=code" + + "&client_id=" + clientId + + "&redirect_uri=" + redirectUri + + "&scope=" + scope + + "&state=" + state; + response.sendRedirect(authorizationLocation); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java new file mode 100644 index 0000000000..87aa8bc668 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -0,0 +1,76 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.Base64; + +@WebServlet(urlPatterns = "/callback") +public class CallbackServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //Error: + String error = request.getParameter("error"); + if (error != null) { + request.setAttribute("error", error); + dispatch("/", request, response); + return; + } + String localState = (String) request.getSession().getAttribute("CLIENT_LOCAL_STATE"); + if (!localState.equals(request.getParameter("state"))) { + request.setAttribute("error", "The state attribute doesn't match !!"); + dispatch("/", request, response); + return; + } + + String code = request.getParameter("code"); + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "authorization_code"); + form.param("code", code); + form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); + + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue()) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + + request.getSession().setAttribute("tokenResponse", tokenResponse); + dispatch("/", request, response); + } + + private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + private String getAuthorizationHeaderValue() { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + String token = clientId + ":" + clientSecret; + String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); + return "Basic " + encodedString; + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java new file mode 100644 index 0000000000..bbe850917b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java @@ -0,0 +1,49 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.*; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/downstream") +public class DownstreamCallServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { + resp.setContentType("text/html;charset=UTF-8"); + String action = request.getParameter("action"); + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target(config.getValue("resourceServerUri", String.class)); + WebTarget resourceWebTarget; + String response = null; + JsonObject tokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + if ("read".equals(action)) { + resourceWebTarget = webTarget.path("resource/read"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .get(String.class); + } else if ("write".equals(action)) { + resourceWebTarget = webTarget.path("resource/write"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .post(Entity.text("body string"), String.class); + } + PrintWriter out = resp.getWriter(); + out.println(response); + out.flush(); + out.close(); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..26dc730361 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml @@ -0,0 +1,19 @@ + + + + + localConnector-1.0 + cdi-2.0 + jsp-2.3 + mpConfig-1.3 + jaxrsClient-2.1 + jsonp-1.1 + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d66f4f6a74 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,12 @@ +#Client registration +client.clientId=webappclient +client.clientSecret=webappclientsecret +client.redirectUri=http://localhost:9180/callback +client.scope=resource.read resource.write + +#Provider +provider.authorizationUri=http://127.0.0.1:9080/authorize +provider.tokenUri=http://127.0.0.1:9080/token + +#Resource Server +resourceServerUri=http://localhost:9280/api \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..0203894c1b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,5 @@ + + + index.jsp + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp new file mode 100644 index 0000000000..23fec70f33 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -0,0 +1,97 @@ +<%@ page import="org.eclipse.microprofile.config.Config" %> +<%@ page import="org.eclipse.microprofile.config.ConfigProvider" %> + + + + + + OAuth2 Client + + + + + +<% + Config config1 = ConfigProvider.getConfig(); +%> + +
"> + Error : ${error} +
+ +
+

OAuth2 Authorization Server

+
+

Client Registration :

+
    +
  • client_id: <%=config1.getValue("client.clientId", String.class)%> +
  • +
  • client_secret: <%=config1.getValue("client.clientSecret", String.class)%> +
  • +
  • redirect_uri: <%=config1.getValue("client.redirectUri", String.class)%> +
  • +
  • scope: <%=config1.getValue("client.scope", String.class)%> +
  • +
+

Authorization Server :

+
    +
  • authorization_uri: <%=config1.getValue("provider.authorizationUri", String.class)%> +
  • +
  • token_uri: <%=config1.getValue("provider.tokenUri", String.class)%> +
  • +
+
+
+

OAuth2 Client

+
+

Token Request :

+ + +

Token Response:

+
    +
  • access_token: ${tokenResponse.getString("access_token")}
  • +
  • scope: ${tokenResponse.getString("scope")}
  • +
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
+
+
+

OAuth2 Resource Server Call

+
+ + +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/pom.xml b/oauth2-framework-impl/oauth2-resource-server/pom.xml new file mode 100644 index 0000000000..9b58c33472 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + oauth2-resource-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9280 + 8643 + http://localhost:9080 + http://localhost:9280 + + + + + org.eclipse.microprofile.jwt + microprofile-jwt-auth-api + 1.1 + provided + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java new file mode 100644 index 0000000000..835e80a416 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.oauth2.resource.server; + +import org.eclipse.microprofile.auth.LoginConfig; + +import javax.annotation.security.DeclareRoles; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +@DeclareRoles({"resource.read", "resource.write"}) +@LoginConfig(authMethod = "MP-JWT") +public class OAuth2ResourceServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java new file mode 100644 index 0000000000..300de83c6d --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.resource.server.secure; + +import org.eclipse.microprofile.jwt.JsonWebToken; + +import javax.annotation.security.RolesAllowed; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; +import java.util.UUID; + +@Path("/resource") +@RequestScoped +public class ProtectedResource { + + @Inject + private JsonWebToken principal; + + @GET + @RolesAllowed("resource.read") + @Path("/read") + public Response read() { + //DoStaff + return Response.ok("Hello, " + principal.getName()).build(); + } + + @POST + @RolesAllowed("resource.write") + @Path("/write") + public Response write() { + //DoStaff + return Response.ok("Hello, " + principal.getName()) + .header("location", UUID.randomUUID().toString()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c54d698359 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml @@ -0,0 +1,20 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jsonp-1.1 + mpConfig-1.3 + mpJwt-1.1 + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..be6919ec50 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +mp.jwt.verify.publickey.location=/META-INF/public-key.pem +mp.jwt.verify.issuer=http://localhost:9080 \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2777559c20 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html new file mode 100644 index 0000000000..7ea29c1097 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html @@ -0,0 +1,37 @@ + + + + + Eclipse MicroProfile demo + + + +

MicroProfile

+ +Hello JAX-RS endpoint
+ + +

Config

+Injected config values
+Config values by lookup
+ + + + + + + + + +

JWT Auth

+Look at readme.md on how to test protected endpoint. + + + + + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/pom.xml b/oauth2-framework-impl/pom.xml new file mode 100644 index 0000000000..281103660b --- /dev/null +++ b/oauth2-framework-impl/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + false + RELEASE + 2.6.4 + + + + + javax + javaee-web-api + 8.0 + provided + + + org.eclipse.microprofile.config + microprofile-config-api + 1.3 + provided + + + + + ${project.artifactId} + + + ${basedir}/src/main/resources + + **/*.* + + + + true + ${basedir}/src/main/liberty + + **/*.* + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${openliberty.maven.version} + + + package-server + package + + create-server + install-apps + + + target/wlp-package + + + + + + io.openliberty + openliberty-webProfile8 + ${openliberty.version} + zip + + target/classes/config/server.xml + ${project.build.directory}/${project.build.finalName}.war + project + ${project.basedir}/src/main/liberty/server + apps + true + + + + + + + oauth2-authorization-server + oauth2-resource-server + oauth2-client + + diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml index fbce0ea072..93b1e68264 100644 --- a/optaplanner/pom.xml +++ b/optaplanner/pom.xml @@ -18,11 +18,6 @@ optaplanner-core 7.9.0.Final
- - - - -
\ No newline at end of file diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 4b81e27333..f0e921bf37 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,9 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 parent-boot-2 0.0.1-SNAPSHOT - parent-boot-2 + parent-boot-2 pom Parent for all Spring Boot 2 modules @@ -13,7 +13,7 @@ 1.0.0-SNAPSHOT - + org.springframework.boot @@ -28,7 +28,7 @@ io.rest-assured rest-assured - + org.springframework.boot spring-boot-starter-test @@ -36,22 +36,22 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + thin-jar @@ -75,9 +75,9 @@ - 3.1.0 + 3.3.0 - 1.0.21.RELEASE - 2.1.3.RELEASE + 1.0.22.RELEASE + 2.1.6.RELEASE diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index b1c6854eae..b7d12e2ba4 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -13,13 +13,6 @@ 1.0.0-SNAPSHOT - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - - @@ -31,6 +24,7 @@ + io.rest-assured @@ -88,4 +82,11 @@ + + + 3.1.0 + + 1.0.21.RELEASE + 2.2.0.M3 + diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 6f7fe6c102..d993fad3c6 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -26,6 +26,11 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap + + spring-milestone + Spring Milestone Repository + http://repo.spring.io/milestone + @@ -40,7 +45,7 @@ org.springframework.boot spring-boot-dependencies - 2.0.1.RELEASE + 2.2.0.M4 pom import @@ -80,6 +85,10 @@ ktor-gson ${ktor.io.version} + + com.fasterxml.jackson.module + jackson-module-kotlin + org.jetbrains.kotlin diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index d7eea44989..ab66cf19bf 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -23,14 +23,36 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + 4.3.22.RELEASE - 5.0.2 + 1.6.1 \ No newline at end of file diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 84df8cf30a..f85924b801 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -23,14 +23,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test 5.1.4.RELEASE - 5.0.2 5.1.4.RELEASE diff --git a/patterns/design-patterns-2/pom.xml b/patterns/design-patterns-2/pom.xml index 5c3e70b046..392035ab84 100644 --- a/patterns/design-patterns-2/pom.xml +++ b/patterns/design-patterns-2/pom.xml @@ -38,6 +38,5 @@ 1.8 1.8 16.0.2 - 3.5
diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 605fdc0d6e..1c611f05d2 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -20,3 +20,4 @@ - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) - [Currying in Java](https://www.baeldung.com/java-currying) +- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index ac201ad653..e6bff64f9e 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -48,6 +48,7 @@ ${grep4j.version} + UTF-8 1.8 diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java index 374de31ba9..986c1d9660 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public abstract class AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java index 7b8771ca41..4d5e3bde24 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public interface AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java index 3bf20cfc85..5f994bad89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java index 92d5f94245..37f419b6e2 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthTokenProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java index cd927932ad..3a0c35a9b9 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class SamlAuthenticationProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java index 3885b2b79b..39038b1374 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java index 9877039446..14dc93b8fc 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java index 30dcf08e89..878b67e0cf 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java @@ -1,10 +1,10 @@ -package com.baeldung.pattern.command.client; +package com.baeldung.command.client; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileApplication { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java index c90a162b88..74adce0116 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java index b908e2c44c..f0462622e3 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java index 506bb23d99..2d0267d315 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; @FunctionalInterface public interface TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java index bd2213706e..67c6dedd89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.invoker; +package com.baeldung.command.invoker; -import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.command.command.TextFileOperation; import java.util.ArrayList; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java index c0b2d3c41e..0163102256 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.receiver; +package com.baeldung.command.receiver; public class TextFile { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java index 9ab34c3cd8..353a369837 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java @@ -1,11 +1,9 @@ -package com.baeldung.pattern.templatemethod.application; +package com.baeldung.templatemethod.application; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.StandardComputer; -import com.baeldung.pattern.templatemethod.model.HighEndComputer; -import com.baeldung.pattern.templatemethod.model.ComputerBuilder; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.ComputerBuilder; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class Application { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java index 1419398f62..129a8d4c65 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; import java.util.HashMap; import java.util.Map; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java index 515a6940f5..b5c7ee3987 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java index 0684b1b233..55394d1df6 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class HighEndComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java index c992aa2bff..2ee6f93f9b 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class HighEndComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java index 4e1d857016..3abe240316 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class StandardComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java index cc81dddc1b..da2c2e9b2d 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class StandardComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java index 824b104f81..4556232815 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -1,14 +1,9 @@ package com.baeldung.chainofresponsibility; -import org.junit.Test; -import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; -import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; import static org.junit.Assert.assertTrue; +import org.junit.Test; + public class ChainOfResponsibilityIntegrationTest { private static AuthenticationProcessor getChainOfAuthProcessor() { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java index 1c72bfdd2f..eac62313f7 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java index a7bc1f3025..3e47f10366 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java index efafa0d8a2..3861b1109e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java @@ -1,14 +1,17 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; import java.util.function.Function; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileOperationExecutorUnitTest { @@ -65,4 +68,11 @@ public class TextFileOperationExecutorUnitTest { Function executeMethodReference = SaveTextFileOperation::execute; assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt"); } + + @Test + public void givenOpenAndSaveTextFileOperationExecutorInstance_whenCalledExecuteOperationWithLambdaExpression_thenBothAssertion() { + TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor(); + assertThat(textFileOperationExecutor.executeOperation(() -> "Opening file file1.txt")).isEqualTo("Opening file file1.txt"); + assertThat(textFileOperationExecutor.executeOperation(() -> "Saving file file1.txt")).isEqualTo("Saving file file1.txt"); + } } diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java index 32b83897c9..e35c785f3e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java @@ -1,9 +1,11 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.receiver.TextFile; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.receiver.TextFile; public class TextFileUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java index 4ad4debb27..2c721be5da 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -1,14 +1,16 @@ package com.baeldung.templatemethod.test; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; -import org.junit.Assert; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; + +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class TemplateMethodPatternIntegrationTest { diff --git a/patterns/dip/pom.xml b/patterns/dip/pom.xml index dac3f824f2..bc793c0090 100644 --- a/patterns/dip/pom.xml +++ b/patterns/dip/pom.xml @@ -19,13 +19,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.1 + ${assertj-core.version} test @@ -34,6 +34,7 @@ UTF-8 11 11 + 3.12.1 diff --git a/patterns/pom.xml b/patterns/pom.xml index 875af67d55..2be9d2519e 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -51,7 +51,6 @@ - 3.0.0 9.4.0.v20161208 diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index 4dcef07695..46e774edff 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -317,7 +317,6 @@ 2.6 1.1.3 1.2.5.Final-redhat-1 - 3.5
diff --git a/persistence-modules/elasticsearch/README.md b/persistence-modules/elasticsearch/README.md new file mode 100644 index 0000000000..691e855314 --- /dev/null +++ b/persistence-modules/elasticsearch/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Jest – Elasticsearch Java Client](https://www.baeldung.com/elasticsearch-jest) diff --git a/persistence-modules/elasticsearch/pom.xml b/persistence-modules/elasticsearch/pom.xml index ceed88aa24..f7bfdb44de 100644 --- a/persistence-modules/elasticsearch/pom.xml +++ b/persistence-modules/elasticsearch/pom.xml @@ -20,12 +20,16 @@ io.searchbox jest - 6.3.1 + ${jest.version} com.fasterxml.jackson.core jackson-databind - 2.9.6 + ${jackson.version} + + + 6.3.1 + diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 203cb2f8e4..99374f9135 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -3,3 +3,5 @@ - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) +- [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index bb8ebdab65..e90d7463bd 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -2,6 +2,9 @@ + hibernate-mapping + 1.0.0-SNAPSHOT + 4.0.0 com.baeldung @@ -10,10 +13,6 @@ .. - hibernate-mapping - 1.0.0-SNAPSHOT - 4.0.0 - org.hibernate @@ -45,12 +44,12 @@ javax.money money-api - 1.0.3 + ${money-api.version} org.javamoney moneta - 1.3 + ${moneta.version} pom @@ -59,7 +58,7 @@ hibernate-mapping - src/test/resources + src/main/resources true @@ -70,6 +69,8 @@ 3.8.0 6.0.16.Final 3.0.1-b11 + 1.0.3 + 1.3
diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 65% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index e522dab48d..46e6824f42 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -1,8 +1,9 @@ package com.baeldung.hibernate.oneToMany.config; import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateAnnotationUtil { @@ -12,16 +13,12 @@ public class HibernateAnnotationUtil { private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); + Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; + } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml similarity index 67% rename from persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml index 14d853d3fd..9b97c03935 100644 --- a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml +++ b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml @@ -4,11 +4,11 @@ "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> - com.mysql.jdbc.Driver - mypassword - jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true - myuser - org.hibernate.dialect.MySQLDialect + org.h2.Driver + + jdbc:h2:mem:spring_hibernate_one_to_many + sa + org.hibernate.dialect.H2Dialect create thread true diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties diff --git a/persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql b/persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql rename to persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 90% rename from persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java index b3a091ebf1..3bc5a6e12a 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -10,7 +10,7 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.HSQLDialect; +import org.hibernate.dialect.H2Dialect; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.AfterClass; @@ -18,6 +18,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; + import com.baeldung.hibernate.oneToMany.model.Cart; import com.baeldung.hibernate.oneToMany.model.Items; @@ -33,9 +34,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest { @BeforeClass public static void beforeTests() { Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") .setProperty("hibernate.hbm2ddl.auto", "update"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml index 2ccac03bd3..7ac29b1720 100644 --- a/persistence-modules/hibernate-ogm/pom.xml +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -19,31 +19,31 @@ org.hibernate.ogm hibernate-ogm-mongodb - 5.4.0.Final + ${hibernate.version} org.hibernate.ogm hibernate-ogm-neo4j - 5.4.0.Final + ${hibernate.version} org.jboss.narayana.jta narayana-jta - 5.5.23.Final + ${narayana-jta.version} junit junit - 4.12 + ${junit.version} test org.easytesting fest-assert - 1.4 + ${fest-assert.version} test @@ -57,4 +57,10 @@ + + + 5.4.0.Final + 1.4 + 5.5.23.Final + \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 68008bc8fe..65322f0cea 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -33,3 +33,4 @@ - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 7a9fdc0d34..bf4b2d27ec 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -60,7 +60,7 @@ org.hibernate hibernate-testing - 5.2.2.Final + ${hibernate.version} com.fasterxml.jackson.core @@ -70,7 +70,7 @@ net.bytebuddy byte-buddy - 1.9.5 + ${byte-buddy.version} @@ -91,7 +91,7 @@ javax.xml.bind jaxb-api - 2.3.0 + ${jaxb-api.version} @@ -120,6 +120,8 @@ 3.8.0 1.21 0.9 + 1.9.5 + 2.3.0
diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 7edcd168e9..5a99217f45 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -13,3 +13,4 @@ - [Defining JPA Entities](https://www.baeldung.com/jpa-entities) - [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) - [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) +- [Persisting Enums in JPA](https://www.baeldung.com/jpa-persisting-enums-in-jpa) diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 51cc401332..ced049d281 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -34,7 +34,7 @@ javax.persistence javax.persistence-api - 2.2 + ${javax.persistence-api.version} @@ -104,10 +104,12 @@ + 5.4.0.Final 2.7.4-RC1 42.2.5 + 2.2 \ No newline at end of file diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 0f5efedb96..35e59e60c6 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -1,42 +1,49 @@ - - 4.0.0 - com.baeldung - java-mongodb - 1.0-SNAPSHOT + + 4.0.0 + com.baeldung + java-mongodb + 1.0-SNAPSHOT java-mongodb - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + - + - - de.flapdoodle.embedmongo - de.flapdoodle.embedmongo - ${flapdoodle.version} - test - + + de.flapdoodle.embedmongo + de.flapdoodle.embedmongo + ${flapdoodle.version} + test + + + org.mongodb + mongo-java-driver + ${mongo.version} + + + dev.morphia.morphia + core + ${morphia.version} + - - org.mongodb - mongo-java-driver - ${mongo.version} - + - - - - 1.8 - 1.8 - 3.10.1 - 1.11 - + + 1.8 + 1.8 + 3.10.1 + 1.11 + 1.5.3 + diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java new file mode 100644 index 0000000000..b45aee6068 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.morphia.domain; + +import java.util.List; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Author { + + @Id + private String name; + private List books; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + +} diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java new file mode 100644 index 0000000000..172c916ad9 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -0,0 +1,116 @@ +package com.baeldung.morphia.domain; + +import java.util.HashSet; +import java.util.Set; + +import dev.morphia.annotations.Embedded; +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Field; +import dev.morphia.annotations.Id; +import dev.morphia.annotations.Index; +import dev.morphia.annotations.IndexOptions; +import dev.morphia.annotations.Indexes; +import dev.morphia.annotations.Property; +import dev.morphia.annotations.Reference; +import dev.morphia.annotations.Validation; + +@Entity("Books") +@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) }) +@Validation("{ price : { $gt : 0 } }") +public class Book { + @Id + private String isbn; + @Property + private String title; + private String author; + @Embedded + private Publisher publisher; + @Property("price") + private double cost; + @Reference + private Set companionBooks; + + public Book() { + + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public double getCost() { + return cost; + } + + public void addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + } + + public Book(String isbn, String title, String author, double cost, Publisher publisher) { + this.isbn = isbn; + this.title = title; + this.author = author; + this.cost = cost; + this.publisher = publisher; + this.companionBooks = new HashSet<>(); + } + + @Override + public String toString() { + return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + long temp; + temp = Double.doubleToLongBits(cost); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); + result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); + result = prime * result + ((title == null) ? 0 : title.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; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) + return false; + if (isbn == null) { + if (other.isbn != null) + return false; + } else if (!isbn.equals(other.isbn)) + return false; + if (publisher == null) { + if (other.publisher != null) + return false; + } else if (!publisher.equals(other.publisher)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java new file mode 100644 index 0000000000..b9e054e9ab --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java @@ -0,0 +1,70 @@ +package com.baeldung.morphia.domain; + +import org.bson.types.ObjectId; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Publisher { + + @Id + private ObjectId id; + private String name; + + public Publisher() { + + } + + public Publisher(ObjectId id, String name) { + this.id = id; + this.name = name; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Catalog [id=" + id + ", name=" + name + "]"; + } + + @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(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Publisher other = (Publisher) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java new file mode 100644 index 0000000000..f508c5f525 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java @@ -0,0 +1,131 @@ +package com.baeldung.morphia; + +import static dev.morphia.aggregation.Group.grouping; +import static dev.morphia.aggregation.Group.push; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Iterator; +import java.util.List; + +import org.bson.types.ObjectId; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.baeldung.morphia.domain.Author; +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; +import dev.morphia.query.Query; +import dev.morphia.query.UpdateOperations; + +@Ignore +public class MorphiaIntegrationTest { + + private static Datastore datastore; + private static ObjectId id = new ObjectId(); + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), "library"); + datastore.ensureIndexes(); + } + + @Test + public void givenDataSource_whenCreateEntity_thenEntityCreated() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + Book companionBook = new Book("9789332575103", "Java Performance Companion", "Tom Kirkman", 1.95, publisher); + book.addCompanionBooks(companionBook); + datastore.save(companionBook); + datastore.save(book); + + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(1, books.size()); + assertEquals(book, books.get(0)); + } + + @Test + public void givenDocument_whenUpdated_thenUpdateReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + UpdateOperations updates = datastore.createUpdateOperations(Book.class) + .inc("price", 1); + datastore.update(query, updates); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(4.95, books.get(0) + .getCost()); + } + + @Test + public void givenDocument_whenDeleted_thenDeleteReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + datastore.delete(query); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(0, books.size()); + } + + @Test + public void givenDocument_whenAggregated_thenResultsCollected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + datastore.save(new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher)); + datastore.save(new Book("9781449313142", "Learning Perl", "Mark Pence", 2.95, publisher)); + datastore.save(new Book("9787564100476", "Learning Python", "Mark Pence", 5.95, publisher)); + datastore.save(new Book("9781449368814", "Learning Scala", "Mark Pence", 6.95, publisher)); + datastore.save(new Book("9781784392338", "Learning Go", "Jonathan Sawyer", 8.95, publisher)); + + Iterator authors = datastore.createAggregation(Book.class) + .group("author", grouping("books", push("title"))) + .out(Author.class); + + assertTrue(authors.hasNext()); + + } + + @Test + public void givenDocument_whenProjected_thenOnlyProjectionReceived() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .project("title", true) + .find() + .toList(); + assertEquals(books.size(), 1); + assertEquals("Learning Java", books.get(0) + .getTitle()); + assertNull(books.get(0) + .getAuthor()); + } + +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/README.md b/persistence-modules/jpa-hibernate-cascade-type/README.md new file mode 100644 index 0000000000..d7f3d7dd7c --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Overview of JPA/Hibernate Cascade Types](https://www.baeldung.com/jpa-cascade-types) diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index 8cfc2a5fa2..a45f297a6b 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -2,6 +2,10 @@ + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + com.baeldung parent-modules @@ -9,10 +13,6 @@ ../../ - jpa-hibernate-cascade-type - 4.0.0 - 1.0.0-SNAPSHOT - org.hibernate diff --git a/persistence-modules/spring-boot-mysql/.gitignore b/persistence-modules/spring-boot-mysql/.gitignore new file mode 100644 index 0000000000..96136ab255 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project +.mvn/ \ No newline at end of file diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml new file mode 100644 index 0000000000..6be58332aa --- /dev/null +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + spring-boot-mysql + 0.1.0 + spring-boot-mysql + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + 2.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-devtools + true + + + mysql + mysql-connector-java + + + + + spring-boot-mysql-timezone + + + src/main/resources + true + + + + + + + + + UTF-8 + 8.0.12 + + + diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..d69f66fc7a --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,20 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import javax.annotation.PostConstruct; +import java.util.TimeZone; + +@SpringBootApplication +public class Application { + + @PostConstruct + void started() { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java new file mode 100644 index 0000000000..48864269fe --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java @@ -0,0 +1,27 @@ +package com.baeldung.boot; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class Controller { + + @Autowired + UserRepository userRepository; + + @GetMapping + public User get() { + User user = new User(); + userRepository.save(user); + return user; + } + + @GetMapping("/find") + public List find() { + List users = userRepository.findAll(); + return users; + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java new file mode 100644 index 0000000000..55cb97dec2 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java @@ -0,0 +1,40 @@ +package com.baeldung.boot; + + +import org.springframework.data.annotation.CreatedDate; + +import javax.persistence.*; +import java.util.Date; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Integer id; + + @Column + private String name; + + @CreatedDate + private Date createdDate = new Date(); + + public Date getCreatedDate() { + return createdDate; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java new file mode 100644 index 0000000000..3c50c30cce --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.io.Serializable; + +@Repository +public interface UserRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml new file mode 100644 index 0000000000..5404555d49 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml @@ -0,0 +1,14 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false + username: root + password: + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + jdbc: + time_zone: UTC \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..90787681cf --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 40f9f40749..f277ef66ca 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -2,3 +2,4 @@ - [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) - [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) +- [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file) diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 585e54bf57..dae5efa6d0 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java new file mode 100644 index 0000000000..d38e11c055 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.mongodb.daos; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import com.baeldung.mongodb.models.Photo; + +public interface PhotoRepository extends MongoRepository { + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java new file mode 100644 index 0000000000..13f1a3cd19 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java @@ -0,0 +1,51 @@ +package com.baeldung.mongodb.models; + +import org.bson.types.Binary; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "photos") +public class Photo { + + @Id + private String id; + + private String title; + + private Binary image; + + public Photo(String title) { + super(); + this.title = title; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Binary getImage() { + return image; + } + + public void setImage(Binary image) { + this.image = image; + } + + @Override + public String toString() { + return "Photo [id=" + id + ", title=" + title + ", image=" + image + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java new file mode 100644 index 0000000000..617f0cdbfd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java @@ -0,0 +1,39 @@ +package com.baeldung.mongodb.models; + +import java.io.InputStream; + +public class Video { + private String title; + private InputStream stream; + + public Video() { + super(); + } + + public Video(String title) { + super(); + this.title = title; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public InputStream getStream() { + return stream; + } + + public void setStream(InputStream stream) { + this.stream = stream; + } + + @Override + public String toString() { + return "Video [title=" + title + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java new file mode 100644 index 0000000000..d8d7541c76 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java @@ -0,0 +1,30 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; + +import org.bson.BsonBinarySubType; +import org.bson.types.Binary; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.daos.PhotoRepository; +import com.baeldung.mongodb.models.Photo; + +@Service +public class PhotoService { + + @Autowired + private PhotoRepository photoRepo; + + public Photo getPhoto(String id) { + return photoRepo.findById(id).get(); + } + + public String addPhoto(String title, MultipartFile file) throws IOException { + Photo photo = new Photo(title); + photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes())); + photo = photoRepo.insert(photo); + return photo.getId(); + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java new file mode 100644 index 0000000000..ade1f7c73a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java @@ -0,0 +1,44 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; + +import org.bson.types.ObjectId; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.gridfs.GridFsOperations; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.client.gridfs.model.GridFSFile; + +@Service +public class VideoService { + + @Autowired + private GridFsTemplate gridFsTemplate; + + @Autowired + private GridFsOperations operations; + + public Video getVideo(String id) throws IllegalStateException, IOException { + GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); + Video video = new Video(); + video.setTitle(file.getMetadata().get("title").toString()); + video.setStream(operations.getResource(file).getInputStream()); + return video; + } + + public String addVideo(String title, MultipartFile file) throws IOException { + DBObject metaData = new BasicDBObject(); + metaData.put("type", "video"); + metaData.put("title", title); + ObjectId id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData); + return id.toString(); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java new file mode 100644 index 0000000000..4d5746f0d8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java @@ -0,0 +1,43 @@ +package com.baeldung.mongodb.web; + +import java.io.IOException; +import java.util.Base64; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Photo; +import com.baeldung.mongodb.services.PhotoService; + +@Controller +public class PhotoController { + + @Autowired + private PhotoService photoService; + + @GetMapping("/photos/{id}") + public String getPhoto(@PathVariable String id, Model model) { + Photo photo = photoService.getPhoto(id); + model.addAttribute("title", photo.getTitle()); + model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData())); + return "photos"; + } + + @GetMapping("/photos/upload") + public String uploadPhoto(Model model) { + model.addAttribute("message", "hello"); + return "uploadPhoto"; + } + + @PostMapping("/photos/add") + public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) throws IOException { + String id = photoService.addPhoto(title, image); + return "redirect:/photos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java new file mode 100644 index 0000000000..313ce9e650 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java @@ -0,0 +1,51 @@ +package com.baeldung.mongodb.web; + +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.FileCopyUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.baeldung.mongodb.services.VideoService; + +@Controller +public class VideoController { + + @Autowired + private VideoService videoService; + + @GetMapping("/videos/{id}") + public String getVideo(@PathVariable String id, Model model) throws IllegalStateException, IOException { + Video video = videoService.getVideo(id); + model.addAttribute("title", video.getTitle()); + model.addAttribute("url", "/videos/stream/" + id); + return "videos"; + } + + @GetMapping("/videos/stream/{id}") + public void streamVideo(@PathVariable String id, HttpServletResponse response) throws IllegalStateException, IOException { + Video video = videoService.getVideo(id); + FileCopyUtils.copy(video.getStream(), response.getOutputStream()); + } + + @GetMapping("/videos/upload") + public String uploadVideo(Model model) { + model.addAttribute("message", "hello"); + return "uploadVideo"; + } + + @PostMapping("/videos/add") + public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) throws IOException { + String id = videoService.addVideo(title, file); + return "redirect:/videos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties index 5b1b8000d0..6548f2b28a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -1,8 +1,13 @@ spring.application.name=spring-boot-persistence -server.port=${PORT:0} +server.port=8082 #spring boot mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=springboot-mongo +spring.thymeleaf.cache=false + +spring.servlet.multipart.max-file-size=256MB +spring.servlet.multipart.max-request-size=256MB +spring.servlet.multipart.enabled=true \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html new file mode 100644 index 0000000000..f99e9caa8b --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html @@ -0,0 +1,14 @@ + + + +Upload Files MongoDB + + +

Home Page

+
Message
+
+ Upload new Photo +

+ Upload new Video + + diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html new file mode 100644 index 0000000000..b5d56d020a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html @@ -0,0 +1,10 @@ + + +

View Photo

+ Title: name +
+ sample +

+ Back to home page + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html new file mode 100644 index 0000000000..6d51c06d8f --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html @@ -0,0 +1,15 @@ + + + +

Upload new Photo

+
+ Title: +
+ Image: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html new file mode 100644 index 0000000000..ebc29d98e2 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html @@ -0,0 +1,15 @@ + + + +

Upload new Video

+
+ Title: +
+ Video: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html new file mode 100644 index 0000000000..b0ee0fc577 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html @@ -0,0 +1,15 @@ + + +

View Video

+ Title: title +
+
+ + + +

+ Back to home page + + \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..89e729da86 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,67 @@ +package org.baeldung; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4c69245f65 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EclipselinkSpringDataApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3772e22137 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 3bd62cbd45..1f7de81c02 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,4 @@ - [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml index fbc19810ef..08be64670b 100644 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -29,7 +29,7 @@ net.ttddyy datasource-proxy - 1.4.1 + ${datasource-proxy.version} @@ -42,4 +42,8 @@ spring-oxm
+ + + 1.4.1 +
\ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index a7788065c9..af92f331d1 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -37,14 +37,14 @@ org.testcontainers postgresql - 1.10.6 + ${testcontainers.postgresql.version} test org.postgresql postgresql - 42.2.5 + ${postgresql.version} @@ -66,7 +66,7 @@ com.google.guava guava - 21.0 + ${guava.version} @@ -92,6 +92,9 @@ com.baeldung.boot.Application + 1.10.6 + 42.2.5 + 21.0
\ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..db7b156415 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6cc5c15af --- /dev/null +++ b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 7156cdf071..33ad3a5267 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -21,7 +21,7 @@ org.springframework.data spring-data-releasetrain - Lovelace-SR3 + Lovelace-SR9 pom @@ -95,7 +95,7 @@ - 2.1.2.RELEASE + 2.1.9.RELEASE 4.1.4 1.1.3 1.9.2 diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5bf54fc0bd --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) +@ActiveProfiles(profiles = "test") +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6652345595 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.redis.config.RedisConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..09bf0255a0 --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index ec35f35bb3..4349492370 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -93,7 +93,6 @@ 8.5.8 19.0 - 3.5 diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..956d5279a3 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +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 SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index 16e55cb0c0..e27775c76f 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -146,7 +146,6 @@ 21.0 - 3.5
diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 6f8d83aa9d..426944c149 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,7 +9,6 @@ - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) -- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) ### Quick Start diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml index 4289c9c3d5..c22342a34a 100644 --- a/persistence-modules/spring-hibernate4/pom.xml +++ b/persistence-modules/spring-hibernate4/pom.xml @@ -7,10 +7,10 @@ spring-hibernate4 + parent-spring-4 com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + 0.0.1-SNAPSHOT + ../../parent-spring-4 @@ -167,7 +167,6 @@ 19.0 - 3.5 4.4.1 4.5 @@ -176,7 +175,6 @@ 2.7 - 1.6.1
diff --git a/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 0fdffad8db..0961cabaff 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -174,11 +174,7 @@ 21.0 - 3.5 3.8.0 - - - 2.6
\ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..291e49d0c4 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.baeldung.config.PersistenceJPAConfigL2Cache; +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.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 1afacab164..d0b3f5fe29 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -147,7 +147,6 @@ 21.0 - 3.5 3.8.0
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index 9fae34d99e..e202e45b32 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -39,7 +39,7 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java index 9ba4ebdb6d..eef085f386 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java @@ -16,6 +16,7 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils; +import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; @@ -27,6 +28,8 @@ public class EmployeeDAO { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private SimpleJdbcInsert simpleJdbcInsert; + + private SimpleJdbcCall simpleJdbcCall; @Autowired public void setDataSource(final DataSource dataSource) { @@ -36,7 +39,9 @@ public class EmployeeDAO { namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE"); - + + // Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall + //simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE"); } public int getCountOfEmployees() { @@ -110,4 +115,15 @@ public class EmployeeDAO { final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); return updateCounts; } + + public Employee getEmployeeUsingSimpleJdbcCall(int id) { + SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); + Map out = simpleJdbcCall.execute(in); + + Employee emp = new Employee(); + emp.setFirstName((String) out.get("FIRST_NAME")); + emp.setLastName((String) out.get("LAST_NAME")); + + return emp; + } } diff --git a/pom.xml b/pom.xml index d67622feb7..81ae255005 100644 --- a/pom.xml +++ b/pom.xml @@ -1,18 +1,18 @@ + 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 com.baeldung parent-modules 1.0.0-SNAPSHOT - parent-modules + parent-modules pom - - quarkus - + + quarkus + @@ -57,11 +57,11 @@ test - org.junit.jupiter - junit-jupiter-api + org.junit.jupiter + junit-jupiter-api ${junit-jupiter.version} test - + org.hamcrest hamcrest-core @@ -123,22 +123,22 @@ - - org.junit.platform - junit-platform-surefire-provider - ${junit-platform.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - - + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + org.apache.maven.plugins @@ -312,6 +312,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -328,62 +332,62 @@ parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - blade + blade - bootique + bootique - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 core-java-modules/core-java-lambdas @@ -422,7 +426,6 @@ drools dubbo - easy-random ethereum feign @@ -462,6 +465,7 @@ java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams @@ -476,83 +480,83 @@ jaxb - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries - kotlin-libraries-2 + + kotlin-libraries + kotlin-libraries-2 - - libraries - libraries-2 - libraries-data - libraries-apache-commons - libraries-primitive - libraries-security - libraries-server - linkrest - logging-modules - lombok - lucene + + libraries + libraries-2 + libraries-data + libraries-apache-commons + libraries-primitive + libraries-security + libraries-server + libraries-http + libraries-io + linkrest + logging-modules + lombok + lucene - mapstruct - maven - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules - quarkus + persistence-modules + quarkus - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines rsocket - rxjava - rxjava-2 - software-security/sql-injection-samples + rxjava + rxjava-2 + software-security/sql-injection-samples tensorflow-java spring-boot-flowable @@ -562,238 +566,241 @@ - - default-second - - + + default-second + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-webflux - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito + spring-5 + spring-5-webflux + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-2 + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-testing - spring-boot-vue - spring-boot-libraries + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-kotlin + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-testing + spring-boot-vue + spring-boot-libraries - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + + + + + - spring-core - spring-core-2 - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + + spring-dispatcher-servlet + spring-drools - spring-ehcache - spring-ejb - spring-exceptions + spring-ehcache + + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth spring-security-mvc-jsonview - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + + spring-vertx - spring-vault - spring-vertx + - spring-webflux-amqp + spring-zuul - spring-zuul + static-analysis + stripe + structurizr + struts-2 - static-analysis - stripe - structurizr - struts-2 + testing-modules - testing-modules + twilio + Twitter4J - twilio - Twitter4J + undertow - undertow + vertx + vertx-and-rxjava + video-tutorials + vraptor - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + wicket - wicket - - xml - xmlunit-2 - xstream + xml + xstream tensorflow-java spring-boot-flowable spring-security-kerberos - + - + spring-context @@ -820,6 +827,7 @@ spring-5 spring-5-data-reactive spring-5-reactive + spring-5-reactive-2 spring-5-reactive-client spring-5-reactive-security spring-5-security @@ -838,6 +846,7 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter + spring-boot-di greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database @@ -925,7 +934,6 @@ spring-state-machine spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf - spring-userservice spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource @@ -941,570 +949,573 @@ - - default-heavy - - + + default-heavy + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 - core-kotlin-io + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 + core-kotlin-io - jenkins/hello-world - jws + jenkins/hello-world + jhipster + jws - libraries + libraries + persistence-modules/hibernate5 + persistence-modules/hibernate-mapping + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql + vaadin + vavr + + - vaadin - - + + integration-lite-first - - integration-lite-first + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + bootique - bootique + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 + + + core-java-modules/core-java-arrays + core-java-modules/core-java-collections + core-java-modules/core-java-collections-list + core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-array-list + core-java-modules/core-java-collections-set + core-java-modules/core-java-concurrency-basic + core-java-modules/core-java-concurrency-collections + core-java-modules/core-java-io + core-java-modules/core-java-nio + core-java-modules/core-java-security + core-java-modules/core-java-lang-syntax + core-java-modules/core-java-lang + core-java-modules/core-java-lang-oop + core-java-modules/core-java-lang-oop-2 + core-java-modules + core-java-modules/core-java-networking + core-java-modules/core-java-perf + core-java-modules/core-java-sun + core-scala + couchbase + custom-pmd - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - - - core-java-modules/core-java-arrays - core-java-modules/core-java-collections - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-nio - core-java-modules/core-java-security - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-scala - couchbase - custom-pmd + dagger + data-structures + ddd + deeplearning4j + disruptor + dozer + drools + dubbo - dagger - data-structures - ddd - deeplearning4j - disruptor - dozer - drools - dubbo + ethereum - ethereum + feign + flyway-cdi-extension - feign - flyway-cdi-extension + geotools + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc + gson + guava + guava-collections + guava-modules + + guice - geotools - google-cloud - google-web-toolkit - - - graphql/graphql-java - grpc - gson - guava - guava-collections - guava-modules - - guice + hazelcast + helidon + httpclient + httpclient-simple + hystrix - hazelcast - helidon - httpclient - httpclient-simple - hystrix + image-processing + immutables - image-processing - immutables - - jackson - jackson-2 - jackson-simple - java-collections-conversions - java-collections-maps - java-collections-maps-2 - - java-ee-8-security-api - java-lite - java-numbers - java-rmi - java-spi - java-streams - - java-strings - java-strings-2 - java-vavr-stream - java-websocket - javafx - javax-servlets - javaxval - jaxb - + java-ee-8-security-api + java-lite + java-numbers + java-numbers-2 + java-rmi + java-spi + java-streams + + java-strings + java-strings-2 + java-vavr-stream + java-websocket + javafx + javax-servlets + javaxval + jaxb + - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries + + kotlin-libraries - - libraries - libraries-data - libraries-apache-commons - libraries-security - libraries-server - linkrest - logging-modules - lombok - lucene + + libraries + libraries-data + libraries-apache-commons + libraries-security + libraries-server + libraries-http + linkrest + logging-modules + lombok + lucene - mapstruct - maven - - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules + persistence-modules - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines - rsocket - rxjava - rxjava-2 + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines + rsocket + rxjava + rxjava-2 - + - + - - integration-lite-second + + integration-lite-second - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-5 + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-2 + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-vue + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-vue - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-core-2 - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools spring-ehcache - spring-ejb - spring-exceptions + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + spring-vault + spring-vertx - spring-vault - spring-vertx + spring-webflux-amqp - spring-webflux-amqp + spring-zuul - spring-zuul + static-analysis + stripe + structurizr + struts-2 - static-analysis - stripe - structurizr - struts-2 + testing-modules - testing-modules + twilio + Twitter4J - twilio - Twitter4J + undertow - undertow + vertx + vertx-and-rxjava + video-tutorials + vraptor - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + wicket - wicket + xml + xstream + - xml - xmlunit-2 - xstream + - + + integration-heavy - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - integration-heavy + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + core-java-modules/core-java + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + jenkins/hello-world + jhipster + jws - core-java-modules/core-java - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 + libraries - jenkins/hello-world - jws + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - libraries + vaadin + vavr + - persistence-modules/hibernate5 - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql - - vaadin - - - + @@ -1538,7 +1549,7 @@ 1.1.7 - + 2.21.0 3.7.0 1.6.0 @@ -1552,6 +1563,8 @@ 1.6.0 2.21.0 2.5 + 2.6 + 3.5 1.4 3.0.0 3.1.0 diff --git a/quarkus/README.md b/quarkus/README.md index 01009eab3e..8116d16cb7 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) +- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) diff --git a/ratpack/README.md b/ratpack/README.md index 14bc3f6c74..78e2f8ccfc 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -6,3 +6,4 @@ - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) - [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava) +- [Ratpack with Groovy](https://www.baeldung.com/ratpack-groovy) diff --git a/rest-with-spark-java/README.md b/rest-with-spark-java/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rest-with-spark-java/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml deleted file mode 100644 index fc78ac6b86..0000000000 --- a/rest-with-spark-java/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung - rest-with-spark-java - 1.0-SNAPSHOT - rest-with-spark-java - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - com.sparkjava - spark-core - ${spark-core.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - - 2.5.4 - - - diff --git a/rest-with-spark-java/src/main/java/com/baeldung/Router.java b/rest-with-spark-java/src/main/java/com/baeldung/Router.java deleted file mode 100644 index 3482184e1e..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/Router.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung; - -import static spark.Spark.after; -import static spark.Spark.before; -import static spark.Spark.delete; -import static spark.Spark.get; -import static spark.Spark.post; -import static spark.Spark.port; - -import com.baeldung.domain.Book; -import com.baeldung.service.LibraryService; - -public class Router { - - public static void main( String[] args ){ - - port(8080); - - before((request, response) -> { - - //do some filtering stuff - - }); - - after((request, response) -> { - response.type("application/json"); - }); - - get("ListOfBooks", (request, response) -> { - return LibraryService.view(); - }); - - get("SearchBook/:title", (request, response) -> { - return LibraryService.view(request.params("title")); - }); - - post("AddBook/:title/:author/:publisher", (request, response) -> { - Book book = new Book(); - book.setTitle(request.params("title")); - book.setAuthor(request.params("author")); - book.setPublisher(request.params("publisher")); - return LibraryService.add(book); - }); - - delete("DeleteBook/:title", (request, response) -> { - return LibraryService.delete(request.params("title")); - }); - - } -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java b/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java deleted file mode 100644 index 977d5d9f89..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.domain; - -public class Book { - - private String title; - private String author; - private String publisher; - - public Book() {} - - public Book(String title, String author, String publisher) { - super(); - this.title = title; - this.author = author; - this.publisher = publisher; - } - - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - public String getPublisher() { - return publisher; - } - public void setPublisher(String publisher) { - this.publisher = publisher; - } - - protected boolean canEqual(Object other) { - return other instanceof Book; - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof Book)) return false; - Book other = (Book) o; - if (!other.canEqual((Object)this)) return false; - if (this.getTitle() == null ? other.getTitle() != null : !this.getTitle().equals(other.getTitle())) return false; - return true; - } - -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java b/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java deleted file mode 100644 index e4ca4c270c..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -public class LibraryService { - - private static ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); - private static Map library = new HashMap(); - - public static String view() throws JsonProcessingException { - List books = new ArrayList(); - library.forEach((key, value) -> { - books.add(value); - }); - return mapper.writeValueAsString(books); - } - - public static String view(String title) throws JsonProcessingException { - return mapper.writeValueAsString(library.get(title)); - } - - public static String add(Book book) throws JsonProcessingException { - library.put(book.getTitle(), book); - return mapper.writeValueAsString(book); - } - - public static String delete(String title) throws JsonProcessingException { - Book deletedBook = library.remove(title); - return mapper.writeValueAsString(deletedBook); - } - -} diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java deleted file mode 100644 index 9e24879767..0000000000 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.baeldung; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class AppLiveTest extends TestCase { - - ObjectMapper mapper = new ObjectMapper(); - - public AppLiveTest( String testName ) { - super( testName ); - } - - public static Test suite() { - return new TestSuite( AppLiveTest.class ); - } - - public void testApp() throws IOException, ClassNotFoundException { - - URL url; - HttpURLConnection conn; - BufferedReader br; - String output; - StringBuffer resp; - Book book; - Book temp; - - url = new URL("http://localhost:8080/AddBook/Odessy/YannMartel/GreenLeaves"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.getContent(); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Odessy","YannMartel","GreenLeaves"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/AddBook/Twilight/StephenieMeyer/LittleBrown"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - List books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - books.add(new Book("Twilight","StephenieMeyer","LittleBrown")); - - List listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - url = new URL("http://localhost:8080/SearchBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/DeleteBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("DELETE"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - conn.disconnect(); - - } - -} diff --git a/resteasy/pom.xml b/resteasy/pom.xml index ca4124abca..8aea8077f9 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -143,7 +143,6 @@ 3.0.19.Final - 2.5 1.6.1 diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index b12b479614..5c3256319e 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -16,13 +16,10 @@ - - org.springframework.boot spring-boot-starter-jdbc - org.apache.derby derby @@ -43,18 +40,14 @@ lombok provided - org.springframework.boot spring-boot-starter-data-jpa - org.hibernate hibernate-jpamodelgen - - org.springframework.boot spring-boot-devtools diff --git a/spf4j/README.md b/spf4j/README.md new file mode 100644 index 0000000000..a39cd01b5e --- /dev/null +++ b/spf4j/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to SPF4J](https://www.baeldung.com/spf4j) diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index 9fccec673a..1c707f4d87 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -6,12 +6,14 @@ 0.0.1-SNAPSHOT jar spf4j-aspects-app + parent-modules com.baeldung 1.0.0-SNAPSHOT ../../ + org.spf4j @@ -29,6 +31,7 @@ ${org.slf4j.version} + spf4j-aspects-app @@ -75,6 +78,7 @@ + UTF-8 8.6.10 diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index ae346065ef..9f490d9f06 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -6,12 +6,14 @@ 0.0.1-SNAPSHOT jar spf4j-core-app + parent-modules com.baeldung 1.0.0-SNAPSHOT ../../ + org.spf4j @@ -29,6 +31,7 @@ ${org.slf4j.version} + spf4j-core-app @@ -75,6 +78,7 @@ + UTF-8 8.6.10 diff --git a/spring-4/src/test/java/org/baeldung/SpringContextTest.java b/spring-4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cccdaff0cd --- /dev/null +++ b/spring-4/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.flips.ApplicationConfig; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 8c16851de0..5372803842 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -1,9 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-5-data-reactive - spring-5-data-reactive + spring-5-data-reactive jar @@ -49,11 +49,11 @@ ${kotlin.version} test - + io.reactivex.rxjava2 rxjava - + org.springframework spring-test @@ -68,6 +68,44 @@ de.flapdoodle.embed.mongo test + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework + spring-tx + ${spring-tx.version} + + + + org.springframework.data + spring-data-r2dbc + ${spring-data-r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${r2dbc-h2.version} + + + com.h2database + h2 + ${h2.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + @@ -79,7 +117,7 @@ kotlin-maven-plugin ${kotlin-maven-plugin.version} - + compile @@ -123,7 +161,7 @@ - + org.apache.maven.plugins maven-compiler-plugin @@ -131,13 +169,13 @@ ${java.version} - default-compile none - default-testCompile @@ -162,9 +200,30 @@ + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + 1.2.40 1.2.40 + 5.2.0.M2 + 1.0.0.M2 + 0.8.0.M8 + 4.5.2 + 1.4.199 diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java new file mode 100644 index 0000000000..557b6ff42a --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.r2dbc") +public class R2dbcApplication { + + public static void main(String[] args) { + SpringApplication.run(R2dbcApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java new file mode 100644 index 0000000000..17eac7fee2 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.r2dbc.configuration; + +import io.r2dbc.h2.H2ConnectionConfiguration; +import io.r2dbc.h2.H2ConnectionFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; + +@Configuration +//@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") +public class R2DBCConfiguration extends AbstractR2dbcConfiguration { + @Bean + public H2ConnectionFactory connectionFactory() { + return new H2ConnectionFactory( + H2ConnectionConfiguration.builder() + .url("mem:testdb;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=4") + .username("sa") + .build()); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java new file mode 100644 index 0000000000..1926997e97 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java @@ -0,0 +1,16 @@ +package com.baeldung.r2dbc.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Player { + @Id + Integer id; + String name; + Integer age; +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java new file mode 100644 index 0000000000..33b653140e --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc.repository; + +import com.baeldung.r2dbc.model.Player; +import org.springframework.data.r2dbc.repository.query.Query; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import reactor.core.publisher.Flux; + +public interface PlayerRepository extends ReactiveCrudRepository { + + @Query("select id, name, age from player where name = $1") + Flux findAllByName(String name); + + @Query("select * from player where age = $1") + Flux findByAge(int age); +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java new file mode 100644 index 0000000000..a31ef4458d --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.r2dbc; + + +import com.baeldung.r2dbc.model.Player; +import com.baeldung.r2dbc.repository.PlayerRepository; +import io.r2dbc.h2.H2ConnectionFactory; +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.data.r2dbc.core.DatabaseClient; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.Arrays; +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class R2dbcApplicationIntegrationTest { + + + @Autowired + PlayerRepository playerRepository; + + @Autowired + DatabaseClient client; + + @Autowired + H2ConnectionFactory factory; + + + @Before + public void setup() { + + Hooks.onOperatorDebug(); + + List statements = Arrays.asList(// + "DROP TABLE IF EXISTS player;", + "CREATE table player (id INT AUTO_INCREMENT NOT NULL, name VARCHAR2, age INT NOT NULL);"); + + statements.forEach(it -> client.execute() // + .sql(it) // + .fetch() // + .rowsUpdated() // + .as(StepVerifier::create) // + .expectNextCount(1) // + .verifyComplete()); + + } + + @Test + public void whenDeleteAll_then0IsExpected() { + + + playerRepository.deleteAll() + .as(StepVerifier::create) + .expectNextCount(0) + .verifyComplete(); + } + + @Test + public void whenInsert6_then6AreExpected() { + + insertPlayers(); + + playerRepository.findAll() + .as(StepVerifier::create) + .expectNextCount(6) + .verifyComplete(); + } + + @Test + public void whenSearchForCR7_then1IsExpected() { + + insertPlayers(); + + playerRepository.findAllByName("CR7") + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + } + + @Test + public void whenSearchFor32YearsOld_then2AreExpected() { + insertPlayers(); + + playerRepository.findByAge(32) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + } + + @Test + public void whenBatchHas2Operations_then2AreExpected() { + Mono.from(factory.create()) + .flatMapMany(connection -> Flux.from(connection + .createBatch() + .add("select * from player") + .add("select * from player") + .execute())) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + + } + + private void insertPlayers() { + List players = Arrays.asList( + new Player(1, "Kaka", 37), + new Player(2, "Messi", 32), + new Player(3, "Mbappé", 20), + new Player(4, "CR7", 34), + new Player(5, "Lewandowski", 30), + new Player(6, "Cavani", 32) + ); + + playerRepository.saveAll(players).subscribe(); + } +} + diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 5fb8f66f71..302080a8b4 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 com.baeldung @@ -51,12 +52,10 @@ org.jetbrains.kotlin kotlin-stdlib-jre8 - ${kotlin.version} org.jetbrains.kotlin kotlin-reflect - ${kotlin.version} com.fasterxml.jackson.module @@ -91,7 +90,6 @@ - ${project.basedir}/src/main/kotlin ${project.basedir}/src/test/kotlin @@ -132,11 +130,43 @@ + + org.codehaus.mojo + build-helper-maven-plugin + + + generate-sources + + add-source + + + + ${basedir}/src/main/java + ${basedir}/src/main/kotlin + + + + + test-compile + test-compile + + add-test-source + + + + ${basedir}/src/test/java + ${basedir}/src/test/kotlin + + + + + - + 2.9.0 1.1.2 + com.baeldung.Spring5Application diff --git a/spring-5-reactive-2/.gitignore b/spring-5-reactive-2/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/spring-5-reactive-2/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/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/spring-5-reactive-2/README.md b/spring-5-reactive-2/README.md new file mode 100644 index 0000000000..bbb45e9f8c --- /dev/null +++ b/spring-5-reactive-2/README.md @@ -0,0 +1 @@ +## Spring 5 Reactive Project diff --git a/spring-5-reactive-2/pom.xml b/spring-5-reactive-2/pom.xml new file mode 100644 index 0000000000..668e0e5cf9 --- /dev/null +++ b/spring-5-reactive-2/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + com.baeldung + spring-5-reactive-2 + 0.0.1-SNAPSHOT + spring-5-reactive-2 + jar + spring 5 sample project about new features + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.webclient.WebClientApplication + JAR + + + + + + diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java new file mode 100644 index 0000000000..8d294955f3 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java @@ -0,0 +1,13 @@ +package com.baeldung.webclient; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Tweet { + private String text; + private String username; +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java new file mode 100644 index 0000000000..fecaca25ef --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java @@ -0,0 +1,20 @@ +package com.baeldung.webclient; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@RestController +public class TweetsSlowServiceController { + + @GetMapping("/slow-service-tweets") + private List getAllTweets() throws Exception { + Thread.sleep(2000L); // delay + return Arrays.asList( + new Tweet("RestTemplate rules", "@user1"), + new Tweet("WebClient is better", "@user2"), + new Tweet("OK, both are useful", "@user1")); + } +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java new file mode 100644 index 0000000000..751e3a9487 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.webclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebClientApplication { + public static void main(String[] args) { + SpringApplication.run(WebClientApplication.class, args); + } +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java new file mode 100644 index 0000000000..73f5724819 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java @@ -0,0 +1,60 @@ +package com.baeldung.webclient; + +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; + +import java.util.List; + +@Slf4j +@RestController +public class WebController { + + private static final int DEFAULT_PORT = 8080; + + @Setter + private int serverPort = DEFAULT_PORT; + + @GetMapping("/tweets-blocking") + public List getTweetsBlocking() { + log.info("Starting BLOCKING Controller!"); + final String uri = getSlowServiceUri(); + + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity> response = restTemplate.exchange( + uri, HttpMethod.GET, null, + new ParameterizedTypeReference>(){}); + + List result = response.getBody(); + result.forEach(tweet -> log.info(tweet.toString())); + log.info("Exiting BLOCKING Controller!"); + return result; + } + + @GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux getTweetsNonBlocking() { + log.info("Starting NON-BLOCKING Controller!"); + Flux tweetFlux = WebClient.create() + .get() + .uri(getSlowServiceUri()) + .retrieve() + .bodyToFlux(Tweet.class); + + tweetFlux.subscribe(tweet -> log.info(tweet.toString())); + log.info("Exiting NON-BLOCKING Controller!"); + return tweetFlux; + } + + private String getSlowServiceUri() { + return "http://localhost:" + serverPort + "/slow-service-tweets"; + } + +} diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java new file mode 100644 index 0000000000..09c3a5fb84 --- /dev/null +++ b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.webclient; + +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.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) +public class WebControllerIntegrationTest { + + @LocalServerPort + int randomServerPort; + + @Autowired + private WebTestClient testClient; + + @Autowired + private WebController webController; + + @Before + public void setup() { + webController.setServerPort(randomServerPort); + } + + @Test + public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { + testClient.get() + .uri("/tweets-blocking") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Tweet.class) + .hasSize(3); + } + + @Test + public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { + testClient.get() + .uri("/tweets-non-blocking") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Tweet.class) + .hasSize(3); + } +} \ No newline at end of file diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..678d04897b --- /dev/null +++ b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveTestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java similarity index 87% rename from spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java index 7360def71e..81e77d9c61 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java @@ -6,7 +6,7 @@ import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component -public class DownstreamServiceReactiveHealthIndicator implements ReactiveHealthIndicator { +public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..479c35d986 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.security.SpringSecurity5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSecurity5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security-cognito/pom.xml b/spring-5-security-cognito/pom.xml index c7314d6f9f..431c9b8d9c 100644 --- a/spring-5-security-cognito/pom.xml +++ b/spring-5-security-cognito/pom.xml @@ -48,7 +48,6 @@ org.springframework.security spring-security-oauth2-jose - org.springframework spring-test diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..729790bd14 --- /dev/null +++ b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index c1f537d2fe..6887f01753 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -28,11 +28,6 @@ - - 1.8 - 2.2.0.M3 - - org.springframework.boot @@ -86,6 +81,7 @@ https://repo.spring.io/milestone + spring-snapshots @@ -101,4 +97,8 @@ https://repo.spring.io/milestone + + + 2.2.0.M3 + diff --git a/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java new file mode 100644 index 0000000000..1997163954 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java @@ -0,0 +1,8 @@ +package com.baeldung.annotationconfigvscomponentscan.components; + +import org.springframework.stereotype.Component; + +@Component +public class AccountService { + +} diff --git a/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java new file mode 100644 index 0000000000..8dd5ae2ef0 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java @@ -0,0 +1,16 @@ +package com.baeldung.annotationconfigvscomponentscan.components; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class UserService { + + @Autowired + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + +} diff --git a/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml new file mode 100644 index 0000000000..ee4bbb6573 --- /dev/null +++ b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java new file mode 100644 index 0000000000..7cd7b81def --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.annotationconfigvscomponentscan.components.AccountService; +import com.baeldung.annotationconfigvscomponentscan.components.UserService; + +public class SpringXMLConfigurationIntegrationTest { + + @Test + public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:annotationconfigvscomponentscan-beans.xml"); + UserService userService = context.getBean(UserService.class); + AccountService accountService = context.getBean(AccountService.class); + Assert.assertNotNull(userService); + Assert.assertNotNull(accountService); + Assert.assertNotNull(userService.getAccountService()); + } + +} diff --git a/spring-5/src/test/java/org/baeldung/SpringContextTest.java b/spring-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..56e8697f5c --- /dev/null +++ b/spring-5/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..14df617b1f --- /dev/null +++ b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.activitiwithspring.ActivitiWithSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +@AutoConfigureTestDatabase +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java new file mode 100644 index 0000000000..41db539265 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ProfileManager { + + @Autowired + private Environment environment; + + public void getActiveProfiles() { + for (final String profileName : environment.getActiveProfiles()) { + System.out.println("Currently active profile - " + profileName); + } + } +} diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java index aa88a3775e..0ae99610f6 100644 --- a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java @@ -12,7 +12,7 @@ public class ScopesIntegrationTest { private static final String NAME_OTHER = "Anna Jones"; @Test - public void testScopeSingleton() { + public void givenSingletonScope_whenSetName_thenEqualNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); @@ -25,7 +25,7 @@ public class ScopesIntegrationTest { } @Test - public void testScopePrototype() { + public void givenPrototypeScope_whenSetNames_thenDifferentNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4d3ed953c4 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-apache-camel/.gitignore b/spring-apache-camel/.gitignore new file mode 100644 index 0000000000..eac473ac50 --- /dev/null +++ b/spring-apache-camel/.gitignore @@ -0,0 +1 @@ +/src/test/destination-folder/* \ No newline at end of file diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt b/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1c098a56ab --- /dev/null +++ b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/.gitignore b/spring-batch/.gitignore new file mode 100644 index 0000000000..0ef6d10b38 --- /dev/null +++ b/spring-batch/.gitignore @@ -0,0 +1 @@ +output.csv \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0de9a07b0a --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..783567cdfa --- /dev/null +++ b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..834f26dacf --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminclient.SpringBootAdminClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminClientApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c185456019 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminserver.SpringBootAdminServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..961d756a68 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.ecommerce.EcommerceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EcommerceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml index 6ea98eb3d0..71c46cb7f5 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -6,15 +6,13 @@ spring-boot-angular 1.0 jar + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../../parent-boot-2 - - 1.8 - @@ -46,5 +44,4 @@ - diff --git a/spring-boot-autoconfiguration/README.MD b/spring-boot-autoconfiguration/README.MD index a71af54dff..dc9cad539a 100644 --- a/spring-boot-autoconfiguration/README.MD +++ b/spring-boot-autoconfiguration/README.MD @@ -3,4 +3,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) \ No newline at end of file +- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) +- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 91692ebfff..5b3b0eb86c 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -38,6 +38,19 @@ mysql mysql-connector-java + + + org.springframework.boot + spring-boot-configuration-processor + 2.1.6.RELEASE + true + + + + org.hsqldb + hsqldb + runtime + @@ -50,12 +63,10 @@ - org.apache.maven.plugins maven-war-plugin - diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java new file mode 100644 index 0000000000..91ea94e43e --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.autoconfiguration.MySQLAutoconfiguration; + +@EnableAutoConfiguration(exclude = { MySQLAutoconfiguration.class}) +@ComponentScan(basePackageClasses = {DatabaseProperties.class}) +public class AnnotationProcessorApplication { + public static void main(String[] args) { + new SpringApplicationBuilder(AnnotationProcessorApplication.class).run(); + } +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java new file mode 100644 index 0000000000..4fb5b408a2 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java @@ -0,0 +1,73 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "database") +public class DatabaseProperties { + + public static class Server { + + /** + * The IP of the database server + */ + private String ip; + + /** + * The Port of the database server. + * The Default value is 443. + * The allowed values are in the range 400-4000. + */ + @Min(400) + @Max(800) + private int port = 443; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + } + + private String username; + private String password; + private Server server; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Server getServer() { + return server; + } + + public void setServer(Server server) { + this.server = server; + } +} \ No newline at end of file diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java new file mode 100644 index 0000000000..350e65b465 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import org.junit.Assert; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnnotationProcessorApplication.class) +@TestPropertySource("classpath:databaseproperties-test.properties") +public class DatabasePropertiesIntegrationTest { + + @Autowired + private DatabaseProperties databaseProperties; + + @Test + public void whenSimplePropertyQueriedThenReturnsPropertyValue() throws Exception { + Assert.assertEquals("Incorrectly bound Username property", "baeldung", databaseProperties.getUsername()); + Assert.assertEquals("Incorrectly bound Password property", "password", databaseProperties.getPassword()); + } + + @Test + public void whenNestedPropertyQueriedThenReturnsPropertyValue() throws Exception { + Assert.assertEquals("Incorrectly bound Server IP nested property", "127.0.0.1", databaseProperties.getServer().getIp()); + Assert.assertEquals("Incorrectly bound Server Port nested property", 3306, databaseProperties.getServer().getPort()); + } + +} diff --git a/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties b/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties new file mode 100644 index 0000000000..c0d1d1f158 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties @@ -0,0 +1,7 @@ +#Simple Properties +database.username=baeldung +database.password=password + +#Nested Properties +database.server.ip=127.0.0.1 +database.server.port=3306 \ No newline at end of file diff --git a/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4340e27fb4 --- /dev/null +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8324fabfca --- /dev/null +++ b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.camel.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9c3b83ea79 --- /dev/null +++ b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.boot.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-crud/pom.xml b/spring-boot-crud/pom.xml index 15ff6c5d11..1d956bdba6 100644 --- a/spring-boot-crud/pom.xml +++ b/spring-boot-crud/pom.xml @@ -54,7 +54,28 @@ org.springframework.boot spring-boot-maven-plugin + + exec + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + @@ -62,4 +83,4 @@ UTF-8 - \ No newline at end of file + diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff3e795778 --- /dev/null +++ b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6ce83fab5 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = GreeterAutoConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b82b67df68 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.greeter.sample.GreeterSampleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreeterSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-data/pom.xml b/spring-boot-data/pom.xml index 8735a54e7b..9c11e09f4a 100644 --- a/spring-boot-data/pom.xml +++ b/spring-boot-data/pom.xml @@ -15,6 +15,30 @@ + + org.springframework.boot + spring-boot-starter-data-redis + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.6.RELEASE + + + + com.h2database + h2 + 1.4.197 + + org.springframework.boot spring-boot-starter-web diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java new file mode 100644 index 0000000000..8e4ee76a25 --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -0,0 +1,16 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; + +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class SpringDataJPA { + + public static void main(String[] args) { + SpringApplication.run(SpringDataJPA.class, args); + } +} diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java new file mode 100644 index 0000000000..865c137a8d --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -0,0 +1,14 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; + +@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) +public class SpringDataMongoDB { + + public static void main(String[] args) { + SpringApplication.run(SpringDataMongoDB.class, args); + } +} diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java new file mode 100644 index 0000000000..9ec831c446 --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java @@ -0,0 +1,14 @@ +package com.baeldung.disableautoconfig; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; + +@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) +public class SpringDataRedis { + + public static void main(String[] args) { + SpringApplication.run(SpringDataRedis.class, args); + } +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java new file mode 100644 index 0000000000..a465979b3c --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataJPA.class) +public class SpringDataJPAIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(DataSource.class); + } + +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java new file mode 100644 index 0000000000..bdfadf76ce --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataMongoDB.class) +public class SpringDataMongoDBIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(MongoTemplate.class); + } + +} diff --git a/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java new file mode 100644 index 0000000000..10133cace3 --- /dev/null +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.disableautoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRedis.class) +public class SpringDataRedisIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(RedisTemplate.class); + } + +} diff --git a/spring-boot-di/README.MD b/spring-boot-di/README.MD new file mode 100644 index 0000000000..78cd163668 --- /dev/null +++ b/spring-boot-di/README.MD @@ -0,0 +1,6 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) diff --git a/spring-boot-di/pom.xml b/spring-boot-di/pom.xml new file mode 100644 index 0000000000..ec40c04566 --- /dev/null +++ b/spring-boot-di/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-boot-mvc + spring-boot-mvc + jar + Module For Spring Boot DI + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.SpringBootDiApplication + JAR + + + + + + + com.baeldung.SpringBootDiApplication + + + diff --git a/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java new file mode 100644 index 0000000000..b9d2d7ecef --- /dev/null +++ b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootDiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootDiApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java index 2377ed7a56..83b91f7860 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -1,10 +1,6 @@ package com.baeldung.componentscan.springapp; -import org.springframework.context.annotation.FilterType; -import org.springframework.stereotype.Component; - import com.baeldung.componentscan.ExampleBean; -import com.baeldung.componentscan.springapp.flowers.Rose; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java index ba29a4e1f5..4362caefbb 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java @@ -1,14 +1,11 @@ package com.baeldung.componentscan.springbootapp; import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.FilterType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import com.baeldung.componentscan.ExampleBean; -import com.baeldung.componentscan.springbootapp.flowers.Rose; @SpringBootApplication //@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals") diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java diff --git a/spring-boot-flowable/pom.xml b/spring-boot-flowable/pom.xml index f9531a1e6a..f7fc943389 100644 --- a/spring-boot-flowable/pom.xml +++ b/spring-boot-flowable/pom.xml @@ -7,12 +7,14 @@ war spring-boot-flowable Spring Boot Flowable Module + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-2 + org.springframework.boot @@ -44,6 +46,7 @@ test + @@ -52,6 +55,7 @@ + 6.4.1 diff --git a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab6e4557d5 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Main.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4effccc083 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.keycloak.SpringBoot; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-kotlin/README.md b/spring-boot-kotlin/README.md new file mode 100644 index 0000000000..dc50c24aa0 --- /dev/null +++ b/spring-boot-kotlin/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Non-blocking Spring Boot with Kotlin Coroutines](http://www.baeldung.com/non-blocking-spring-boot-with-kotlin-coroutines) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml new file mode 100644 index 0000000000..25508c52b9 --- /dev/null +++ b/spring-boot-kotlin/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + spring-boot-kotlin + spring-boot-kotlin + jar + Demo project showing how to use non-blocking in Kotlin with Spring Boot + + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + org.jetbrains.kotlin + kotlin-reflect + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring-boot.version} + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + org.springframework.data + spring-data-r2dbc + ${r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${h2-r2dbc.version} + + + io.r2dbc + r2dbc-spi + ${r2dbc-spi.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.projectreactor + reactor-test + test + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + + + -Xjsr305=strict + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + 1.3.31 + 1.0.0.M1 + 1.0.0.M7 + 1.0.0.BUILD-SNAPSHOT + 1.2.1 + 2.2.0.M2 + + + diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt new file mode 100644 index 0000000000..23af4fe90b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.nonblockingcoroutines + +import org.springframework.boot.SpringApplication.run +import org.springframework.boot.autoconfigure.SpringBootApplication + +@SpringBootApplication +class SpringApplication + +fun main(args: Array) { + run(SpringApplication::class.java, *args) +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt new file mode 100644 index 0000000000..52ef8a708b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt @@ -0,0 +1,32 @@ +package com.baeldung.nonblockingcoroutines.config + +import io.r2dbc.h2.H2ConnectionConfiguration +import io.r2dbc.h2.H2ConnectionFactory +import io.r2dbc.spi.ConnectionFactory +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories + +@Configuration +@EnableR2dbcRepositories +class DatastoreConfig : AbstractR2dbcConfiguration() { + @Value("\${spring.datasource.username}") + private val userName: String = "" + + @Value("\${spring.datasource.password}") + private val password: String = "" + + @Value("\${spring.datasource.dbname}") + private val dbName: String = "" + + @Bean + override fun connectionFactory(): ConnectionFactory { + return H2ConnectionFactory(H2ConnectionConfiguration.builder() + .inMemory(dbName) + .username(userName) + .password(password) + .build()) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt new file mode 100644 index 0000000000..bda1d26278 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt @@ -0,0 +1,19 @@ +package com.baeldung.nonblockingcoroutines.config + +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import kotlinx.coroutines.FlowPreview +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.server.coRouter + +@Configuration +class RouterConfiguration { + + @FlowPreview + @Bean + fun productRoutes(productsHandler: ProductsHandler) = coRouter { + GET("/", productsHandler::findAll) + GET("/{id}", productsHandler::findOne) + GET("/{id}/stock", productsHandler::findOneInStock) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt new file mode 100644 index 0000000000..85938b8be2 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt @@ -0,0 +1,12 @@ +package com.baeldung.nonblockingcoroutines.config + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.client.WebClient + +@Configuration +class WebClientConfiguration { + + @Bean + fun webClient() = WebClient.builder().baseUrl("http://localhost:8080").build() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt new file mode 100644 index 0000000000..91b091859a --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepository +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.bodyToMono +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +class ProductController { + @Autowired + lateinit var webClient: WebClient + @Autowired + lateinit var productRepository: ProductRepository + + @GetMapping("/{id}") + fun findOne(@PathVariable id: Int): Mono { + return productRepository + .getProductById(id) + } + + @GetMapping("/{id}/stock") + fun findOneInStock(@PathVariable id: Int): Mono { + val product = productRepository.getProductById(id) + + val stockQuantity = webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono() + return product.zipWith(stockQuantity) { productInStock, stockQty -> + ProductStockView(productInStock, stockQty) + } + } + + @GetMapping("/stock-service/product/{id}/quantity") + fun getStockQuantity(): Mono { + return Mono.just(2) + } + + @GetMapping("/") + fun findAll(): Flux { + return productRepository.getAllProducts() + } +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt new file mode 100644 index 0000000000..d70d352cda --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.Flow +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType.APPLICATION_JSON +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange + +class ProductControllerCoroutines { + @Autowired + lateinit var webClient: WebClient + + @Autowired + lateinit var productRepository: ProductRepositoryCoroutines + + @GetMapping("/{id}") + suspend fun findOne(@PathVariable id: Int): Product? { + return productRepository.getProductById(id) + } + + @GetMapping("/{id}/stock") + suspend fun findOneInStock(@PathVariable id: Int): ProductStockView { + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ProductStockView(product.await()!!, quantity.await()) + } + + @FlowPreview + @GetMapping("/") + fun findAll(): Flow { + return productRepository.getAllProducts() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt new file mode 100644 index 0000000000..44611fd1de --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt @@ -0,0 +1,15 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product + +class ProductStockView(product: Product, var stockQuantity: Int) { + var id: Int = 0 + var name: String = "" + var price: Float = 0.0f + + init { + this.id = product.id + this.name = product.name + this.price = product.price + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt new file mode 100644 index 0000000000..41c4510e0d --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.handlers + +import com.baeldung.nonblockingcoroutines.controller.ProductStockView +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.stereotype.Component +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange +import org.springframework.web.reactive.function.server.ServerRequest +import org.springframework.web.reactive.function.server.ServerResponse +import org.springframework.web.reactive.function.server.bodyAndAwait +import org.springframework.web.reactive.function.server.json + +@Component +class ProductsHandler( + @Autowired var webClient: WebClient, + @Autowired var productRepository: ProductRepositoryCoroutines) { + + @FlowPreview + suspend fun findAll(request: ServerRequest): ServerResponse = + ServerResponse.ok().json().bodyAndAwait(productRepository.getAllProducts()) + + suspend fun findOneInStock(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ServerResponse.ok().json().bodyAndAwait(ProductStockView(product.await()!!, quantity.await())) + } + + suspend fun findOne(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + return ServerResponse.ok().json().bodyAndAwait(productRepository.getProductById(id)!!) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt new file mode 100644 index 0000000000..c6dcbdc9c4 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt @@ -0,0 +1,7 @@ +package com.baeldung.nonblockingcoroutines.model + +data class Product( + var id: Int = 0, + var name: String = "", + var price: Float = 0.0f +) diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt new file mode 100644 index 0000000000..20c3827c26 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt @@ -0,0 +1,34 @@ +package com.baeldung.nonblockingcoroutines.repository + +import com.baeldung.nonblockingcoroutines.model.Product +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +@Repository +class ProductRepository(private val client: DatabaseClient) { + + fun getProductById(id: Int): Mono { + return client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + } + + fun addNewProduct(name: String, price: Float): Mono { + return client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + } + + fun getAllProducts(): Flux { + return client.select().from("products") + .`as`(Product::class.java) + .fetch() + .all() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt new file mode 100644 index 0000000000..60a19d4d00 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt @@ -0,0 +1,40 @@ +package com.baeldung.nonblockingcoroutines.repository + + +import com.baeldung.nonblockingcoroutines.model.Product +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.reactive.awaitFirstOrNull +import kotlinx.coroutines.reactive.flow.asFlow +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository + +@Repository +class ProductRepositoryCoroutines(private val client: DatabaseClient) { + + suspend fun getProductById(id: Int): Product? = + client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + .awaitFirstOrNull() + + suspend fun addNewProduct(name: String, price: Float) = + client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + .awaitFirstOrNull() + + @FlowPreview + fun getAllProducts(): Flow = + client.select() + .from("products") + .`as`(Product::class.java) + .fetch() + .all() + .log() + .asFlow() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/resources/application.properties b/spring-boot-kotlin/src/main/resources/application.properties new file mode 100644 index 0000000000..0f84ff2d75 --- /dev/null +++ b/spring-boot-kotlin/src/main/resources/application.properties @@ -0,0 +1,8 @@ +logging.level.org.springframework.data.r2dbc=DEBUG +logging.level.org.springframework.web.reactive.function.client.ExchangeFunctions=TRACE +spring.http.log-request-details=true +spring.h2.console.enabled=true +spring.datasource.username=sa +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.password= +spring.datasource.dbname=testdb \ No newline at end of file diff --git a/spring-userservice/src/main/resources/logback.xml b/spring-boot-kotlin/src/main/resources/logback.xml similarity index 100% rename from spring-userservice/src/main/resources/logback.xml rename to spring-boot-kotlin/src/main/resources/logback.xml diff --git a/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt new file mode 100644 index 0000000000..53b1d50f21 --- /dev/null +++ b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt @@ -0,0 +1,58 @@ +package com.baeldung.nonblockingcoroutines + +import com.baeldung.nonblockingcoroutines.config.RouterConfiguration +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.reactive.flow.asFlow +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.BDDMockito.given +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration +import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.test.web.reactive.server.expectBodyList +import org.springframework.web.reactive.function.client.WebClient +import reactor.core.publisher.Flux +import org.springframework.test.context.ContextConfiguration + +@WebFluxTest( + excludeAutoConfiguration = [ReactiveUserDetailsServiceAutoConfiguration::class, ReactiveSecurityAutoConfiguration::class] +) +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [ProductsHandler::class, RouterConfiguration::class]) +class ProductHandlerTest { + + @Autowired + private lateinit var client: WebTestClient + + @MockBean + private lateinit var webClient: WebClient + + @MockBean + private lateinit var productsRepository: ProductRepositoryCoroutines + + + @FlowPreview + @Test + public fun `get all products`() { + val productsFlow = Flux.just( + Product(1, "product1", 1000.0F), + Product(2, "product2", 2000.0F), + Product(3, "product3", 3000.0F) + ).asFlow() + given(productsRepository.getAllProducts()).willReturn(productsFlow) + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk + .expectBodyList() + } + +} diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 6cc60da52c..64696969ca 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -34,6 +34,12 @@ org.springframework.boot spring-boot-starter-log4j2 + + org.projectlombok + lombok + 1.18.4 + provided + diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java new file mode 100644 index 0000000000..5f75dbd5a1 --- /dev/null +++ b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java @@ -0,0 +1,28 @@ +package com.baeldung.springbootlogging; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.extern.slf4j.Slf4j; + +//import lombok.extern.log4j.Log4j2; +//import lombok.extern.apachecommons.CommonsLog; + +@RestController("LombokLoggingController") +@Slf4j +// @CommonsLog (Comment any other Lombok logging annotation and uncomment this +// to work with Apache Commons Logging) +// @Log4j2 (Comment any other Lombok logging annotation and uncomment this to +// work directly with Log4j2) +public class LombokLoggingController { + + @GetMapping("/lombok") + public String index() { + log.trace("A TRACE Message"); + log.debug("A DEBUG Message"); + log.info("An INFO Message"); + log.warn("A WARN Message"); + log.error("An ERROR Message"); + return "Howdy! Check out the Logs to see the output..."; + } +} diff --git a/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9817522e68 --- /dev/null +++ b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootlogging.SpringBootLoggingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLoggingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc-birt/pom.xml b/spring-boot-mvc-birt/pom.xml index 8f41e8410a..bf6bbbf71d 100644 --- a/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-mvc-birt/pom.xml @@ -9,10 +9,12 @@ 0.0.1-SNAPSHOT jar Module For Spring Boot Integration with BIRT + - org.springframework.boot - spring-boot-starter-parent - 2.1.1.RELEASE + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index d5a39cdc9f..e3e3dbdb74 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -12,3 +12,5 @@ - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index e17c1d39b9..fee725847f 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -40,7 +40,7 @@ org.glassfish javax.faces - 2.3.7 + ${javax.faces.version} @@ -108,6 +108,7 @@ 2.9.2 1.10.0 + 2.3.7 com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ops-2/pom.xml b/spring-boot-ops-2/pom.xml index dc5280df48..74fcd79169 100644 --- a/spring-boot-ops-2/pom.xml +++ b/spring-boot-ops-2/pom.xml @@ -3,6 +3,10 @@ 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 + com.baeldung + spring-boot-ops-2 + 0.0.1-SNAPSHOT + spring-boot-ops-2 parent-boot-2 @@ -11,11 +15,6 @@ ../parent-boot-2 - com.baeldung - spring-boot-ops-2 - 0.0.1-SNAPSHOT - spring-boot-ops-2 - org.springframework.boot diff --git a/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java new file mode 100644 index 0000000000..11bbad8bb2 --- /dev/null +++ b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootconfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-parent/README.md b/spring-boot-parent/README.md new file mode 100644 index 0000000000..c3bb4c700d --- /dev/null +++ b/spring-boot-parent/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [The Spring Boot Starter Parent](https://www.baeldung.com/spring-boot-starter-parent) diff --git a/spring-boot-performance/README.md b/spring-boot-performance/README.md new file mode 100644 index 0000000000..015dd759a8 --- /dev/null +++ b/spring-boot-performance/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Lazy Initialization in Spring Boot 2](https://www.baeldung.com/spring-boot-lazy-initialization) diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index bbee7493cc..f51df8bc0c 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -14,11 +14,6 @@ ../parent-boot-performance - - - com.baeldung.lazyinitialization.Application - - org.springframework.boot @@ -42,4 +37,9 @@ + + + + com.baeldung.lazyinitialization.Application + \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java new file mode 100644 index 0000000000..9ebf885d4b --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException { +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..a80802eadf --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cba7f8fc1 --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringBootRestApplication.class}) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java similarity index 94% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java rename to spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java index 592ef5354d..3cfa45421c 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java @@ -10,7 +10,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity -public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { +public class BasicConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java similarity index 90% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java index c091aa6d75..f221712513 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java @@ -1,27 +1,26 @@ package com.baeldung.springbootsecurity.basic_auth; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.web.server.LocalServerPort; -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; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) -public class BasicAuthConfigurationIntegrationTest { +public class BasicConfigurationIntegrationTest { TestRestTemplate restTemplate; URL base; @@ -45,7 +44,7 @@ public class BasicAuthConfigurationIntegrationTest { } @Test - public void whenUserWithWrongCredentialsRequestsHomePage_ThenUnauthorizedPage() throws IllegalStateException, IOException { + public void whenUserWithWrongCredentials_thenUnauthorizedPage() throws IllegalStateException, IOException { restTemplate = new TestRestTemplate("user", "wrongpassword"); ResponseEntity response = restTemplate.getForEntity(base.toString(), String.class); diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml index 84107070bd..12fb14b366 100644 --- a/spring-boot-testing/pom.xml +++ b/spring-boot-testing/pom.xml @@ -15,6 +15,10 @@ + + org.springframework.boot + spring-boot-starter-data-redis + org.springframework.boot spring-boot-starter-web @@ -33,6 +37,13 @@ test + + + it.ozimov + embedded-redis + 0.7.2 + test + org.spockframework diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java new file mode 100644 index 0000000000..6b5b20892f --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java @@ -0,0 +1,24 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; + +@Configuration +@EnableRedisRepositories +public class RedisConfiguration { + + @Bean + public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) { + return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort()); + } + + @Bean + public RedisTemplate redisTemplate(final LettuceConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + return template; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java new file mode 100644 index 0000000000..76f2e1bbfe --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RedisProperties { + private final int redisPort; + private final String redisHost; + + public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) { + this.redisPort = redisPort; + this.redisHost = redisHost; + } + + public int getRedisPort() { + return redisPort; + } + + public String getRedisHost() { + return redisHost; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java new file mode 100644 index 0000000000..41657aaa66 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java @@ -0,0 +1,25 @@ +package com.baeldung.boot.embeddedRedis.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.redis.core.RedisHash; + +import java.util.UUID; + +@RedisHash("user") +public class User { + @Id private UUID id; + private String name; + + public User(UUID id, String name) { + this.id = id; + this.name = name; + } + + public UUID getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java new file mode 100644 index 0000000000..0558bb8482 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.domain.User; +import org.springframework.data.repository.CrudRepository; + +import java.util.UUID; + +public interface UserRepository extends CrudRepository { + +} diff --git a/spring-boot-testing/src/main/resources/application.properties b/spring-boot-testing/src/main/resources/application.properties index e378aacdd5..8dc7f6e3c3 100644 --- a/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-testing/src/main/resources/application.properties @@ -1,3 +1,6 @@ +# embedded redis +spring.redis.host= localhost +spring.redis.port= 6379 # security spring.security.user.name=john diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java new file mode 100644 index 0000000000..f3c8b9a954 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java new file mode 100644 index 0000000000..b4748bcd38 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java @@ -0,0 +1,28 @@ +package com.baeldung.boot.embeddedRedis; + +import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; +import org.springframework.boot.test.context.TestConfiguration; +import redis.embedded.RedisServer; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@TestConfiguration +public class TestRedisConfiguration { + + private final RedisServer redisServer; + + public TestRedisConfiguration(final RedisProperties redisProperties) { + this.redisServer = new RedisServer(redisProperties.getRedisPort()); + } + + @PostConstruct + public void postConstruct() { + redisServer.start(); + } + + @PreDestroy + public void preDestroy() { + redisServer.stop(); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9577ccf0e8 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; +import com.baeldung.boot.embeddedRedis.domain.User; +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.junit4.SpringRunner; + +import java.util.UUID; + +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestRedisConfiguration.class) +public class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Test + public void shouldSaveUser_toRedis() { + final UUID id = UUID.randomUUID(); + final User user = new User(id, "name"); + + final User saved = userRepository.save(user); + + assertNotNull(saved); + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-testing/src/test/resources/application.properties index 9a8b496a8b..0c5b0e13e6 100644 --- a/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-testing/src/test/resources/application.properties @@ -1,3 +1,6 @@ +#embedded redis +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 diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot/.attach_pid12812 b/spring-boot/.attach_pid12812 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-boot/README.MD b/spring-boot/README.MD index d7af3f4614..e159220cbc 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -5,7 +5,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) -- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) - [How to Register a Servlet in Java](http://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) - [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners) @@ -30,10 +29,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) - [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) -- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) -- [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) +- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java new file mode 100644 index 0000000000..52c7881dfc --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java @@ -0,0 +1,30 @@ +package com.baeldung.properties.conversion; + +public class Employee { + + private String name; + private double salary; + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java new file mode 100644 index 0000000000..6ec19cae72 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java @@ -0,0 +1,16 @@ +package com.baeldung.properties.conversion; + +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationPropertiesBinding +public class EmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(data[0], Double.parseDouble(data[1])); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java new file mode 100644 index 0000000000..f00a26e9c4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.properties.conversion; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { PropertyConversion.class, EmployeeConverter.class }) +public class PropertiesConversionApplication { + public static void main(String[] args) { + SpringApplication.run(PropertiesConversionApplication.class, args); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java new file mode 100644 index 0000000000..b9c890306f --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java @@ -0,0 +1,92 @@ +package com.baeldung.properties.conversion; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.convert.DataSizeUnit; +import org.springframework.boot.convert.DurationUnit; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.unit.DataSize; +import org.springframework.util.unit.DataUnit; + +@Configuration +@PropertySource("classpath:conversion.properties") +@ConfigurationProperties(prefix = "conversion") +public class PropertyConversion { + private Duration timeInDefaultUnit; + + private Duration timeInNano; + + @DurationUnit(ChronoUnit.DAYS) + private Duration timeInDays; + + private DataSize sizeInDefaultUnit; + + private DataSize sizeInGB; + + @DataSizeUnit(DataUnit.TERABYTES) + private DataSize sizeInTB; + + private Employee employee; + + // Getters and setters + + public Duration getTimeInDefaultUnit() { + return timeInDefaultUnit; + } + + public void setTimeInDefaultUnit(Duration timeInDefaultUnit) { + this.timeInDefaultUnit = timeInDefaultUnit; + } + + public Duration getTimeInNano() { + return timeInNano; + } + + public void setTimeInNano(Duration timeInNano) { + this.timeInNano = timeInNano; + } + + public Duration getTimeInDays() { + return timeInDays; + } + + public void setTimeInDays(Duration timeInDays) { + this.timeInDays = timeInDays; + } + + public DataSize getSizeInDefaultUnit() { + return sizeInDefaultUnit; + } + + public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { + this.sizeInDefaultUnit = sizeInDefaultUnit; + } + + public DataSize getSizeInGB() { + return sizeInGB; + } + + public void setSizeInGB(DataSize sizeInGB) { + this.sizeInGB = sizeInGB; + } + + public DataSize getSizeInTB() { + return sizeInTB; + } + + public void setSizeInTB(DataSize sizeInTB) { + this.sizeInTB = sizeInTB; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java new file mode 100644 index 0000000000..53bad329ea --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.properties.conversion; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.unit.DataSize; + +import com.baeldung.properties.conversion.PropertiesConversionApplication; +import com.baeldung.properties.conversion.PropertyConversion; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PropertiesConversionApplication.class) +@TestPropertySource("classpath:conversion.properties") +public class PropertiesConversionIntegrationTest { + + @Autowired + private PropertyConversion properties; + + @Test + public void whenUseTimeUnitPropertyConversion_thenSuccess() throws Exception { + assertEquals(Duration.ofMillis(10), properties.getTimeInDefaultUnit()); + assertEquals(Duration.ofNanos(9), properties.getTimeInNano()); + assertEquals(Duration.ofDays(2), properties.getTimeInDays()); + } + + @Test + public void whenUseDataSizePropertyConversion_thenSuccess() throws Exception { + assertEquals(DataSize.ofBytes(300), properties.getSizeInDefaultUnit()); + assertEquals(DataSize.ofGigabytes(2), properties.getSizeInGB()); + assertEquals(DataSize.ofTerabytes(4), properties.getSizeInTB()); + } + + @Test + public void whenUseCustomPropertyConverter_thenSuccess() throws Exception { + assertEquals("john", properties.getEmployee().getName()); + assertEquals(2000.0, properties.getEmployee().getSalary()); + } + +} diff --git a/spring-boot/src/test/resources/conversion.properties b/spring-boot/src/test/resources/conversion.properties new file mode 100644 index 0000000000..640442ec33 --- /dev/null +++ b/spring-boot/src/test/resources/conversion.properties @@ -0,0 +1,11 @@ +###### time unit +conversion.timeInDefaultUnit=10 +conversion.timeInNano=9ns +conversion.timeInDays=2 + +###### data size +conversion.sizeInDefaultUnit=300 +conversion.sizeInGB=2GB +conversion.sizeInTB=4 + +conversion.employee=john,2000 \ No newline at end of file diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a5ab1342a1 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudConfigClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..19ca53c4a7 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudConfigServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigServerApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3ac11452d3 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.JobConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..83cb8067cf --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DataFlowServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c456f69979 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowShellApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DataFlowShellApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..42903189d3 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.LogSinkApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LogSinkApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d090e626d2 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeProcessorApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TimeProcessorApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e19b88de90 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeSourceApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TimeSourceApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java new file mode 100644 index 0000000000..7e38329f88 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AdditionalSourcesSimpleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..818e313c98 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java new file mode 100644 index 0000000000..e88ec436c6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7674713ff8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.basic.BasicArchaiusApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BasicArchaiusApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a03bd8c23b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtraConfigsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java new file mode 100644 index 0000000000..5d3bc8e741 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JdbcSourcesApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-aws/.attach_pid23938 b/spring-cloud/spring-cloud-aws/.attach_pid23938 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..98ae3e4895 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 4f9c60a26a..6cbaa5ac2d 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -97,6 +97,7 @@ + Dalston.RELEASE diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dc635cd003 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java new file mode 100644 index 0000000000..a2d1cd1087 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..76b7539b6b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index c55f9bc471..14b0d2f9b1 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -20,8 +20,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index b4be7663e2..674749a48d 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -24,8 +24,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java new file mode 100644 index 0000000000..d879737553 --- /dev/null +++ b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.config.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ConfigServer.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java new file mode 100644 index 0000000000..c6066027f5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.connectors.heroku; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.connectors.heroku.ConnectorsHerokuApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConnectorsHerokuApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index ea71891648..a7ee52e954 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -56,7 +56,6 @@ UTF-8 UTF-8 - 1.8 2.1.1.RELEASE 2.1.4.RELEASE diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e9098b1467 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index dffbd29206..7a0fa7db10 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -31,6 +31,7 @@ spring-boot-starter-data-rest + diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7d77cbbd7a --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractProducerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index e8e3d67805..5afb006d41 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -9,18 +9,18 @@ Spring Cloud Eureka Server and Sample Clients pom - - spring-cloud-eureka-server - spring-cloud-eureka-client - spring-cloud-eureka-feign-client - - com.baeldung.spring.cloud spring-cloud 1.0.0-SNAPSHOT .. + + + spring-cloud-eureka-server + spring-cloud-eureka-client + spring-cloud-eureka-feign-client + diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..a3ed012abb --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java new file mode 100644 index 0000000000..ac8150defa --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.feign.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 7a44e4ae0f..82147cea28 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -29,7 +29,7 @@ org.springframework.cloud spring-cloud-starter-function-web - 1.0.1.RELEASE + ${spring-cloud-function.version} com.amazonaws @@ -40,7 +40,7 @@ com.amazonaws aws-lambda-java-core - 1.1.0 + ${aws-lambda-java-core.version} provided @@ -87,6 +87,7 @@ UTF-8 1.0.1.RELEASE 2.0.2 + 1.1.0 2.0.4.RELEASE diff --git a/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java new file mode 100644 index 0000000000..67411ebd4a --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudFunctionAwsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b7e2acf7a8 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d5f8180f20 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConsumerFeignApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d3260a4517 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConsumerApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java new file mode 100644 index 0000000000..bd871fc1da --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af59614f7c --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.client.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af393cb697 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.backend.KubernetesBackendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..17cb5a5f39 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesFrontendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7c605567d8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..59802d220a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java new file mode 100644 index 0000000000..6e7f99fb0d --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index 002a333749..92de33572b 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -9,7 +9,6 @@ openfeign OpenFeign project for Spring Boot - parent-boot-2 com.baeldung @@ -17,12 +16,6 @@ ../../parent-boot-2 - - 2.0.1.RELEASE - Finchley.SR2 - - - org.springframework.cloud @@ -58,4 +51,9 @@ + + 2.0.1.RELEASE + Finchley.SR2 + + diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java new file mode 100644 index 0000000000..4bf35f74f4 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.cloud.openfeign; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1b4083e7a6 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudRestConfigApplication.class) +public class SpringContextTest { + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..23dbcf8ff6 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 4152552640..c414e584e5 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -13,6 +13,18 @@ 1.0.0-SNAPSHOT + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + org.springframework.boot @@ -78,18 +90,6 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - 2.2.0 Greenwich.SR1 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..02c429acf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.CloudSite; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudSite.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a061928bf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..aec56a574c --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.AuthServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthServer.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java new file mode 100644 index 0000000000..d78a18d557 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.twitterhdfs.aggregate; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AggregateApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml new file mode 100644 index 0000000000..13ad18810e --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml @@ -0,0 +1,109 @@ + + 4.0.0 + + + spring-cloud-stream-kafka + spring-cloud-stream-kafka + Simple Spring Cloud Stream + jar + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + 1.8 + Greenwich.SR1 + + + + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + + org.springframework.cloud + spring-cloud-stream-schema + + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + io.confluent + kafka-avro-serializer + 4.0.0 + + + + org.apache.avro + avro-compiler + 1.8.2 + + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + schemas + generate-sources + + schema + protocol + idl-protocol + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java/ + + + + + + + + + + confluent + https://packages.confluent.io/maven/ + + + + diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java new file mode 100644 index 0000000000..47c060c143 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.cloud.stream.schema.client.EnableSchemaRegistryClient; + +@SpringBootApplication +@EnableBinding(Processor.class) +@EnableSchemaRegistryClient +public class AvroKafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(AvroKafkaApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java new file mode 100644 index 0000000000..38ac94d952 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient; +import org.springframework.cloud.stream.schema.client.SchemaRegistryClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SchemRegistryConfig { + + @Bean + public SchemaRegistryClient schemaRegistryClient(@Value("${spring.cloud.stream.kafka.binder.producer-properties.schema.registry.url}") String endPoint) { + ConfluentSchemaRegistryClient client = new ConfluentSchemaRegistryClient(); + client.setEndpoint(endPoint); + return client; + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java new file mode 100644 index 0000000000..477946dd73 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java @@ -0,0 +1,21 @@ +package com.baeldung.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; + +@Service +public class AvroConsumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(AvroConsumer.class); + + @StreamListener(Processor.INPUT) + public void consumeEmployeeDetails(Employee employeeDetails) { + LOGGER.info("Let's process employee details: {}", employeeDetails); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java new file mode 100644 index 0000000000..b98b27c9fe --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java @@ -0,0 +1,22 @@ +package com.baeldung.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.producer.AvroProducer; + +@RestController +public class AvroController { + + @Autowired + private AvroProducer avroProducer; + + @PostMapping("/employees/{id}/{firstName}/{lastName}") + public String producerAvroMessage(@PathVariable int id, @PathVariable String firstName, @PathVariable String lastName) { + avroProducer.produceEmployeeDetails(id, firstName, lastName); + return "Sent employee details to consumer"; + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java new file mode 100644 index 0000000000..ff7729dd8c --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java @@ -0,0 +1,42 @@ +package com.baeldung.producer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; +import com.baeldung.schema.EmployeeKey; + +@Service +public class AvroProducer { + + @Autowired + private Processor processor; + + public void produceEmployeeDetails(int empId, String firstName, String lastName) { + + // creating employee details + Employee employee = new Employee(); + employee.setId(empId); + employee.setFirstName(firstName); + employee.setLastName(lastName); + employee.setDepartment("IT"); + employee.setDesignation("Engineer"); + + // creating partition key for kafka topic + EmployeeKey employeeKey = new EmployeeKey(); + employeeKey.setId(empId); + employeeKey.setDepartmentName("IT"); + + Message message = MessageBuilder.withPayload(employee) + .setHeader(KafkaHeaders.MESSAGE_KEY, employeeKey) + .build(); + + processor.output() + .send(message); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml new file mode 100644 index 0000000000..2e30c07374 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml @@ -0,0 +1,29 @@ +spring: + cloud: + stream: + default: + producer: + useNativeEncoding: true + consumer: + useNativeEncoding: true + bindings: + input: + destination: employee-details + content-type: application/*+avro + group: group-1 + concurrency: 3 + output: + destination: employee-details + content-type: application/*+avro + kafka: + binder: + producer-properties: + key.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + value.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + schema.registry.url: http://localhost:8081 + consumer-properties: + key.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + value.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + schema.registry.url: http://localhost:8081 + specific.avro.reader: true + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc new file mode 100644 index 0000000000..d18d657e99 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc @@ -0,0 +1,14 @@ +{ + "type": "record", + "name": "EmployeeKey", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "departmentName", + "type": "string" + }] +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc new file mode 100644 index 0000000000..2abf57e4a2 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc @@ -0,0 +1,29 @@ +{ + "type": "record", + "name": "Employee", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "firstName", + "type": "string" + }, + { + "name": "lastName", + "type": "string" + }, + { + "name": "department", + "type": "string", + "default": "IT " + }, + { + "name": "designation", + "type": "string", + "default": "Software Engineer" + } + ] +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0f3b8de901 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MultipleOutputsServiceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..51f0926429 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java new file mode 100644 index 0000000000..73fcbe55f0 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VaultSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b45e7b9889 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreetingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java new file mode 100644 index 0000000000..df7335dfa6 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.helloworld; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = HelloWorldApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..9e3680b244 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java new file mode 100644 index 0000000000..a5350655fb --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.zuul.config; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java new file mode 100644 index 0000000000..b5ddf6f65c --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.zuulratelimitdemo.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.zuulratelimitdemo.ZuulRatelimitDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZuulRatelimitDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 8e4c539e3b..20cd900e00 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -2,15 +2,15 @@ + 4.0.0 + spring-core-2 + com.baeldung parent-spring-5 0.0.1-SNAPSHOT ../parent-spring-5 - 4.0.0 - - spring-core-2 @@ -31,13 +31,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-api - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -54,7 +54,6 @@ 5.1.4.RELEASE - 5.0.2 \ No newline at end of file diff --git a/spring-core/README.md b/spring-core/README.md index d542fa8ed1..18d14b7ecf 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,7 +8,6 @@ - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) - [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) -- [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) - [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation) - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) @@ -24,3 +23,4 @@ - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) - [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 75e9fd7131..7e5a9b3feb 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -87,7 +87,6 @@ 1.4.4.RELEASE 1 20.0 - 2.6 2.5 1.5.2.RELEASE 1.10.19 diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java b/spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java rename to spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index a7a2a9032a..c7a2984045 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -77,7 +78,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final File employeeFile = loadEmployeesWithSpringInternalClass(); final String employees = new String(Files.readAllBytes(employeeFile.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } @@ -112,4 +113,8 @@ public class SpringResourceIntegrationTest { final String employees = new String(Files.readAllBytes(resource.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } + + public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { + return ResourceUtils.getFile("classpath:data/employees.dat"); + } } diff --git a/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b8fa74fc9 --- /dev/null +++ b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7e7fccadef --- /dev/null +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.books.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index eb0fdfea46..6f816986be 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -96,7 +96,6 @@ 3.0-r1655215 - 3.0.0 \ No newline at end of file diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d1de77b1e6 --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springdispatcherservlet.configuration.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9a36a521f1 --- /dev/null +++ b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.drools.service.TaxiFareConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3e9af8a336 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springejbclient.SpringEjbClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringEjbClientApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index ff28ac89bb..45c80f2c9f 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -192,7 +192,6 @@ 19.0 - 3.5 4.4.5 4.5.2 @@ -200,7 +199,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..49b8fe94d1 --- /dev/null +++ b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.freemarker.config.SpringWebConfig; +import com.baeldung.freemarker.config.WebConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e45997b71e --- /dev/null +++ b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.si.security.MessageConsumer; +import com.baeldung.si.security.SecuredDirectChannel; +import com.baeldung.si.security.SecurityConfig; +import com.baeldung.si.security.SecurityPubSubChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, + MessageConsumer.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79ab2f48b8 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 5a12d27180..e053ee7b4b 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -38,7 +38,7 @@ javax.servlet javax.servlet-api - ${servlet-api-version} + ${javax.servlet-api.version} provided @@ -223,11 +223,10 @@ 2.27 - 3.2.0 1.6.1 4.4.9 4.5.5 - 4.0.0 + 4.0.0 1.58 3.10.0 1.5.10.RELEASE diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f480e597b3 --- /dev/null +++ b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.server.config.RestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e0da75c7af --- /dev/null +++ b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.jinq.JinqApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JinqApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 2ed58c0c95..ea4af32216 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -64,7 +64,6 @@ 4.3.4.RELEASE 5.14.1 - 2.6 diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e89faeebb7 --- /dev/null +++ b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:EmbeddedActiveMQ.xml"}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 8bce500a86..8a1fa877da 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -102,7 +102,7 @@ com.h2database h2 - ${com.h2database.version} + ${h2.version} @@ -189,8 +189,6 @@ 3.11.7 - 1.4.193 - 1.0.0 1.5 1.0.0 diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 2fb4c776fe..3d08aaa928 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 2.2.2.RELEASE + 2.2.7.RELEASE \ No newline at end of file diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java index 9353e63ff6..933d2353aa 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java @@ -29,39 +29,36 @@ public class KafkaConsumerConfig { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } + + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(String groupId) { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory(groupId)); + return factory; + } @Bean public ConcurrentKafkaListenerContainerFactory fooKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("foo")); - return factory; + return kafkaListenerContainerFactory("foo"); } @Bean public ConcurrentKafkaListenerContainerFactory barKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("bar")); - return factory; + return kafkaListenerContainerFactory("bar"); } @Bean public ConcurrentKafkaListenerContainerFactory headersKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("headers")); - return factory; + return kafkaListenerContainerFactory("headers"); } @Bean public ConcurrentKafkaListenerContainerFactory partitionsKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("partitions")); - return factory; + return kafkaListenerContainerFactory("partitions"); } @Bean public ConcurrentKafkaListenerContainerFactory filterKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("filter")); + ConcurrentKafkaListenerContainerFactory factory = kafkaListenerContainerFactory("filter"); factory.setRecordFilterStrategy(record -> record.value() .contains("World")); return factory; diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 74786e7926..18bf198948 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -137,7 +137,6 @@ 3.0.2 0.9.10 1.6.1 - 3.7 diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..769a436778 --- /dev/null +++ b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8f0c3d4612 --- /dev/null +++ b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.ldap.javaconfig.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b6a4e8e389 --- /dev/null +++ b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.MocksApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MocksApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-basics/.gitignore b/spring-mvc-basics/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-basics/.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/spring-mvc-basics/README.md b/spring-mvc-basics/README.md new file mode 100644 index 0000000000..b257b3587b --- /dev/null +++ b/spring-mvc-basics/README.md @@ -0,0 +1,18 @@ +========= + +## Spring MVC Basics with Java Configuration Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) +- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) +- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) +- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml new file mode 100644 index 0000000000..8c52c60b65 --- /dev/null +++ b/spring-mvc-basics/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.baeldung + spring-mvc-basics + 0.1-SNAPSHOT + spring-mvc-basics + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + + + + diff --git a/spring-mvc-basics/src/main/java/com/baeldung/Application.java b/spring-mvc-basics/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +package com.baeldung; + +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-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..a76d955e4f --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java @@ -0,0 +1,27 @@ +package com.baeldung.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + + context.scan("com.baeldung"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java similarity index 89% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java index dbd38c1122..42e441f8f9 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java @@ -1,24 +1,24 @@ -package com.baeldung.customvalidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -@Documented -@Constraint(validatedBy = ContactNumberValidator.class) -@Target({ElementType.METHOD, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface ContactNumberConstraint { - - String message() default "Invalid phone number"; - - Class[] groups() default {}; - - Class[] payload() default {}; - -} +package com.baeldung.customvalidator; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Constraint(validatedBy = ContactNumberValidator.class) +@Target({ ElementType.METHOD, ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ContactNumberConstraint { + + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java similarity index 97% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java index dea6b9099b..fe14f3ccf1 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java @@ -1,17 +1,17 @@ -package com.baeldung.customvalidator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class ContactNumberValidator implements ConstraintValidator { - - @Override - public void initialize(ContactNumberConstraint contactNumber) { - } - - @Override - public boolean isValid(String contactField, ConstraintValidatorContext cxt) { - return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); - } - -} +package com.baeldung.customvalidator; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class ContactNumberValidator implements ConstraintValidator { + + @Override + public void initialize(ContactNumberConstraint contactNumber) { + } + + @Override + public boolean isValid(String contactField, ConstraintValidatorContext cxt) { + return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java similarity index 92% rename from spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java rename to spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java index 539a6032a6..1e3591b7aa 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java @@ -1,16 +1,18 @@ package com.baeldung.exception; +import java.util.Collections; +import java.util.Map; + import org.springframework.http.MediaType; import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import java.util.Collections; -import java.util.Map; - @RestController +@ControllerAdvice public class HttpMediaTypeNotAcceptableExceptionExampleController { @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java new file mode 100644 index 0000000000..bdfa1d835a --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..fb0a452219 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,61 @@ +package com.baeldung.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + + private long id; + private String name; + private String contactNumber; + private String workingArea; + + public Employee() { + super(); + } + + public Employee(final long id, final String name, final String contactNumber, final String workingArea) { + this.id = id; + this.name = name; + this.contactNumber = contactNumber; + this.workingArea = workingArea; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + + public String getWorkingArea() { + return workingArea; + } + + public void setWorkingArea(final String workingArea) { + this.workingArea = workingArea; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java similarity index 82% rename from spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java index 12969b6002..b4fe82ab4a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java @@ -2,10 +2,7 @@ package com.baeldung.model; import com.baeldung.customvalidator.FieldsValueMatch; -@FieldsValueMatch.List({ - @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), - @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") -}) +@FieldsValueMatch.List({ @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") }) public class NewUserForm { private String email; private String verifyEmail; diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java index be702a8517..8cea915e6e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java @@ -1,22 +1,22 @@ -package com.baeldung.model; - -import com.baeldung.customvalidator.ContactNumberConstraint; - -public class ValidatedPhone { - - @ContactNumberConstraint - private String phone; - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - @Override - public String toString() { - return phone; - } -} +package com.baeldung.model; + +import com.baeldung.customvalidator.ContactNumberConstraint; + +public class ValidatedPhone { + + @ContactNumberConstraint + private String phone; + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Override + public String toString() { + return phone; + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java new file mode 100644 index 0000000000..9a321f65a2 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -0,0 +1,67 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.ResourceBundleViewResolver; +import org.springframework.web.servlet.view.XmlViewResolver; + +//@EnableWebMvc +//@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(2); + return bean; + } + + @Bean + public ViewResolver resourceBundleViewResolver() { + final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); + bean.setBasename("views"); + bean.setOrder(0); + return bean; + } + + @Bean + public ViewResolver xmlViewResolver() { + final XmlViewResolver bean = new XmlViewResolver(); + bean.setLocation(new ClassPathResource("views.xml")); + bean.setOrder(1); + return bean; + } + + /** + * Spring Boot allows configuring Content Negotiation using properties + */ + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(true) + .favorParameter(true) + .parameterName("mediaType") + .ignoreAcceptHeader(false) + .useRegisteredExtensionsOnly(false) + .defaultContentType(MediaType.APPLICATION_JSON) + .mediaType("xml", MediaType.APPLICATION_XML) + .mediaType("json", MediaType.APPLICATION_JSON); + } +} \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java new file mode 100644 index 0000000000..cbea4c98c6 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -0,0 +1,60 @@ +package com.baeldung.web.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.model.Employee; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @ModelAttribute("employees") + public void initEmployees() { + employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh")); + employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics")); + employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); + } + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { + return employeeMap.get(Id); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("workingArea", employee.getWorkingArea()); + model.addAttribute("id", employee.getId()); + + employeeMap.put(employee.getId(), employee); + + return "employeeView"; + } + + @ModelAttribute + public void addAttributes(final Model model) { + model.addAttribute("msg", "Welcome to the Netherlands!"); + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..e91a914c6d --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java new file mode 100644 index 0000000000..4cc7589bc8 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java @@ -0,0 +1,48 @@ +package com.baeldung.web.controller; + +import java.util.concurrent.ThreadLocalRandom; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.model.Book; + +@RestController +public class ResponseStatusRestController { + + @GetMapping("/teapot") + @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) + public void teaPot() { + } + + @GetMapping("empty") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void emptyResponse() { + } + + @GetMapping("empty-no-responsestatus") + public void emptyResponseWithoutResponseStatus() { + } + + @PostMapping("create") + @ResponseStatus(HttpStatus.CREATED) + public Book createEntity() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } + + @PostMapping("create-no-responsestatus") + public Book createEntityWithoutResponseStatus() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..ce89669fde --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,24 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SampleController { + + @GetMapping("/sample") + public String showForm() { + return "sample"; + } + + @GetMapping("/sample2") + public String showForm2() { + return "sample2"; + } + + @GetMapping("/sample3") + public String showForm3() { + return "sample3"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java similarity index 96% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java index 9b3a6b3a4c..73e1e4bb25 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java @@ -1,32 +1,32 @@ -package com.baeldung.web.controller; - -import com.baeldung.model.ValidatedPhone; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; - -import javax.validation.Valid; - -@Controller -public class ValidatedPhoneController { - - @GetMapping("/validatePhone") - public String loadFormPage(Model m) { - m.addAttribute("validatedPhone", new ValidatedPhone()); - return "phoneHome"; - } - - @PostMapping("/addValidatePhone") - public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { - if (result.hasErrors()) { - return "phoneHome"; - } - - m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); - return "phoneHome"; - } - - -} +package com.baeldung.web.controller; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; + +import com.baeldung.model.ValidatedPhone; + +@Controller +public class ValidatedPhoneController { + + @GetMapping("/validatePhone") + public String loadFormPage(Model m) { + m.addAttribute("validatedPhone", new ValidatedPhone()); + return "phoneHome"; + } + + @PostMapping("/addValidatePhone") + public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { + if (result.hasErrors()) { + return "phoneHome"; + } + + m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); + return "phoneHome"; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties new file mode 100644 index 0000000000..b8a9be0b40 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -0,0 +1,7 @@ +server.servlet.context-path=/spring-mvc-basics + +### Content Negotiation (already defined programatically) +spring.mvc.pathmatch.use-suffix-pattern=true +#spring.mvc.contentnegotiation.favor-path-extension=true +#spring.mvc.contentnegotiation.favor-parameter=true +#spring.mvc.contentnegotiation.parameter-name=mediaType diff --git a/spring-mvc-basics/src/main/resources/mvc-configuration.xml b/spring-mvc-basics/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/resources/views.properties b/spring-mvc-basics/src/main/resources/views.properties new file mode 100644 index 0000000000..06d042b446 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/views.properties @@ -0,0 +1,3 @@ +sample2.(class)=org.springframework.web.servlet.view.JstlView +sample2.url=/WEB-INF/view2/sample2.jsp + diff --git a/spring-mvc-java/src/main/resources/views.xml b/spring-mvc-basics/src/main/resources/views.xml similarity index 65% rename from spring-mvc-java/src/main/resources/views.xml rename to spring-mvc-basics/src/main/resources/views.xml index 83bca5293d..a44d3deae4 100644 --- a/spring-mvc-java/src/main/resources/views.xml +++ b/spring-mvc-basics/src/main/resources/views.xml @@ -1,10 +1,10 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..fa5812faea --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp new file mode 100644 index 0000000000..9a9b879a35 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -0,0 +1,25 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+

${msg}

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp new file mode 100644 index 0000000000..4f4eb0068d --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the index view

+ + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp similarity index 89% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp rename to spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp index b873e9bc5f..ebc9052639 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp @@ -1,38 +1,38 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> - - - - - Sample Form - - - - -
- -

Phone Number

-
${message}
- - - - - - -
- - -
-
- - +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + Sample Form + + + + +
+ +

Phone Number

+
${message}
+ + + + + + +
+ + +
+
+ + diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp new file mode 100644 index 0000000000..c826700a75 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample2 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp new file mode 100644 index 0000000000..b58a0973da --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample3 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2feb9efce1 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java similarity index 76% rename from spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java index e3dcb15de8..577825d8c5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java @@ -1,11 +1,10 @@ package com.baeldung.config; -import com.baeldung.web.controller.handlermapping.WelcomeController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import com.baeldung.web.controller.handlermapping.WelcomeController; @Configuration public class BeanNameUrlHandlerMappingConfig { @@ -16,7 +15,7 @@ public class BeanNameUrlHandlerMappingConfig { } @Bean("/beanNameUrl") - public WelcomeController welcome() { + public WelcomeController welcomeBeanNameMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java index d3a329a387..4072278fee 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -16,7 +16,7 @@ public class HandlerMappingDefaultConfig { } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeDefaultMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java index 2d80dbfeaf..c5fec171a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java @@ -16,14 +16,14 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; public class HandlerMappingPrioritiesConfig { @Bean - BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + BeanNameUrlHandlerMapping beanNameUrlHandlerMappingOrder1() { BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); beanNameUrlHandlerMapping.setOrder(1); return beanNameUrlHandlerMapping; } @Bean - public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + public SimpleUrlHandlerMapping simpleUrlHandlerMappingOrder0() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); simpleUrlHandlerMapping.setOrder(0); Map urlMap = new HashMap<>(); @@ -37,7 +37,7 @@ public class HandlerMappingPrioritiesConfig { return new SimpleUrlMappingController(); } - @Bean("/welcome") + @Bean("/welcome-priorities") public BeanNameHandlerMappingController beanNameHandlerMapping() { return new BeanNameHandlerMappingController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java index c7921c2706..7a366ecbd7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; public class SimpleUrlHandlerMappingConfig { @Bean - public ViewResolver viewResolver() { + public ViewResolver viewResolverSimpleMappingConfig() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); @@ -29,13 +29,13 @@ public class SimpleUrlHandlerMappingConfig { public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); Map urlMap = new HashMap<>(); - urlMap.put("/simpleUrlWelcome", welcome()); + urlMap.put("/simpleUrlWelcome", welcomeSimpleMappingConfig()); simpleUrlHandlerMapping.setUrlMap(urlMap); return simpleUrlHandlerMapping; } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeSimpleMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java new file mode 100644 index 0000000000..797e489080 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.exception; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +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.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@AutoConfigureMockMvc +public class HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest { + + @Autowired + MockMvc mockMvc; + + @Test + public void whenHttpMediaTypeNotAcceptableExceptionTriggered_thenExceptionHandled() throws Exception { + mockMvc.perform(post("/test").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_PDF)) + .andExpect(content().string("acceptable MIME type:application/json")); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java similarity index 51% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java index 2cd225a775..24182f492a 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java @@ -5,46 +5,47 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class ClassValidationMvcIntegrationTest { - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build(); + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()) + .build(); } - + @Test public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.com") - .param("password", "pass") - .param("verifyPassword", "pass")) - .andExpect(model().attribute("message", "Valid form")) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.com") + .param("password", "pass") + .param("verifyPassword", "pass")) + .andExpect(model().attribute("message", "Valid form")) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } - + @Test public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.commmm") - .param("password", "pass") - .param("verifyPassword", "passsss")) - .andExpect(model().errorCount(2)) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.commmm") + .param("password", "pass") + .param("verifyPassword", "passsss")) + .andExpect(model().errorCount(2)) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java similarity index 63% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java index 013cf9c91d..11b72e1650 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java @@ -1,41 +1,43 @@ -package com.baeldung.web.controller; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -public class CustomMVCValidatorIntegrationTest { - - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build(); - } - - @Test - public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{ - this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome")); - } - - @Test - public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone"). - accept(MediaType.TEXT_HTML). - param("phoneInput", "123")). - andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")). - andExpect(view().name("phoneHome")). - andExpect(status().isOk()). - andDo(print()); - } - -} +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class CustomMVCValidatorIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()) + .build(); + } + + @Test + public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception { + this.mockMvc.perform(get("/validatePhone")) + .andExpect(view().name("phoneHome")); + } + + @Test + public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone") + .accept(MediaType.TEXT_HTML) + .param("phoneInput", "123")) + .andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone", "ContactNumberConstraint")) + .andExpect(view().name("phoneHome")) + .andExpect(status().isOk()) + .andDo(print()); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java new file mode 100644 index 0000000000..6500955d23 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerContentNegotiationIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenEndpointUsingJsonSuffixCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlSuffixCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonParameterCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlParameterCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonAcceptHeaderCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlAcceptHeaderCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java new file mode 100644 index 0000000000..5195adabd5 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import java.util.Arrays; +import java.util.Collection; + +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerModelAttributeIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void givenUrlEncodedFormData_whenAddEmployeeEndpointCalled_thenModelContainsMsgAttribute() throws Exception { + Collection formData = Arrays.asList(new BasicNameValuePair("name", "employeeName"), new BasicNameValuePair("id", "99"), new BasicNameValuePair("contactNumber", "123456789")); + String urlEncodedFormData = EntityUtils.toString(new UrlEncodedFormEntity(formData)); + + mockMvc.perform(post("/addEmployee").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .content(urlEncodedFormData)) + .andExpect(status().isOk()) + .andExpect(view().name("employeeView")) + .andExpect(model().attribute("msg", "Welcome to the Netherlands!")); + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java new file mode 100644 index 0000000000..3fbb5da75e --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class RequestMapingShortcutsIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new RequestMappingShortcutsController()) + .build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("GET Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("POST Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PUT Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("DELETE Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PATCH Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java new file mode 100644 index 0000000000..1f37a3750c --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class ResponseStatusRestControllerIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ResponseStatusRestController()) + .build(); + } + + @Test + public void whenTeapotEndpointCalled_thenTeapotResponseObtained() throws Exception { + this.mockMvc.perform(get("/teapot")) + .andExpect(status().isIAmATeapot()); + } + + @Test + public void whenEmptyNoContentEndpointCalled_thenNoContentResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty")) + .andExpect(status().isNoContent()); + } + + @Test + public void whenEmptyWithoutResponseStatusEndpointCalled_then200ResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty-no-responsestatus")) + .andExpect(status().isOk()); + } + + @Test + public void whenCreateWithCreatedEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create")) + .andExpect(status().isCreated()); + } + + @Test + public void whenCreateWithoutResponseStatusEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create-no-responsestatus")) + .andExpect(status().isOk()); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java new file mode 100644 index 0000000000..0b958996c9 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -0,0 +1,33 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.RestAssured; + +public class SampleControllerLiveTest { + + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; + + @Test + public void whenSampleEndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample2EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample2") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample3EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample3") + .then() + .statusCode(HttpStatus.OK.value()); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23be3a1655..87d70c2d29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -5,19 +5,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index c5bd53f1a7..294943f2e2 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -5,27 +5,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookRestController()).build(); } @Test public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc - .perform(get("/books/42")) + .perform(get("/books-rest/42")) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.id").value(42)); diff --git a/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml b/spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml similarity index 100% rename from spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml rename to spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml diff --git a/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index 20912e71e5..5ce2d19414 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -99,7 +99,6 @@ - 2.6 6.0.10.Final 1.3.3 5.2.5.Final diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e35fc8c86c --- /dev/null +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import com.baeldung.springmvcforms.configuration.ApplicationConfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfiguration.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java new file mode 100644 index 0000000000..751df882f9 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung.listbindingexample; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.listbindingexample.ListBindingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ListBindingApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java new file mode 100644 index 0000000000..0b308319b1 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung.sessionattrs; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.sessionattrs.SessionAttrsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SessionAttrsApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3deeb21afc..e67d4f30a1 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -6,29 +6,16 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) -- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) -- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) -- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) -- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) -- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 853d8db64c..cb16e91bc4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -15,8 +15,8 @@ - - org.springframework + + org.springframework spring-webmvc ${spring.version} @@ -34,7 +34,6 @@ javax.servlet jstl ${jstl.version} - @@ -134,17 +133,22 @@ gson 2.8.5 - - org.springframework - spring-websocket - ${spring.version} - + + org.springframework + spring-websocket + ${spring.version} + - - org.springframework - spring-messaging - ${spring.version} - + + org.springframework + spring-messaging + ${spring.version} + + + org.glassfish + javax.el + ${javax.el.version} + @@ -291,7 +295,7 @@ 3.16-beta1 - 3.0.1-b06 + 3.0.1-b09 diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 191d721dfb..44fef92917 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -12,13 +12,11 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @@ -26,8 +24,6 @@ import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.ResourceBundleViewResolver; -import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -97,11 +93,6 @@ public class WebConfig implements WebMvcConfigurer { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", - MediaType.APPLICATION_JSON); - } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { @@ -110,22 +101,6 @@ public class WebConfig implements WebMvcConfigurer { return multipartResolver; } - - @Bean - public ViewResolver xmlViewResolver() { - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } @Override public void extendMessageConverters(final List> converters) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index ef76059567..251287dff8 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,20 +1,29 @@ package com.baeldung.web.controller; -import com.baeldung.model.Employee; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; -import java.util.*; +import com.baeldung.model.Employee; @SessionAttributes("employees") @Controller -@ControllerAdvice public class EmployeeController { Map employeeMap = new HashMap<>(); @@ -35,7 +44,7 @@ public class EmployeeController { public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } - + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { @@ -51,11 +60,6 @@ public class EmployeeController { return "employeeView"; } - @ModelAttribute - public void addAttributes(final Model model) { - model.addAttribute("msg", "Welcome to the Netherlands!"); - } - @RequestMapping(value = "/employees/{name}", method = RequestMethod.GET) @ResponseBody public ResponseEntity> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) { diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java deleted file mode 100644 index 5d4cbe9d78..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.web.controller; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class RequestMappingShortcutsController { - - @GetMapping("/get") - public @ResponseBody ResponseEntity get() { - return new ResponseEntity("GET Response", HttpStatus.OK); - } - - @GetMapping("/get/{id}") - public @ResponseBody ResponseEntity getById(@PathVariable String id) { - return new ResponseEntity("GET Response : " + id, HttpStatus.OK); - } - - @PostMapping("/post") - public @ResponseBody ResponseEntity post() { - return new ResponseEntity("POST Response", HttpStatus.OK); - } - - @PutMapping("/put") - public @ResponseBody ResponseEntity put() { - return new ResponseEntity("PUT Response", HttpStatus.OK); - } - - @DeleteMapping("/delete") - public @ResponseBody ResponseEntity delete() { - return new ResponseEntity("DELETE Response", HttpStatus.OK); - } - - @PatchMapping("/patch") - public @ResponseBody ResponseEntity patch() { - return new ResponseEntity("PATCH Response", HttpStatus.OK); - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java index 111bf023f7..fdb0d75530 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.web.controller.message; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; diff --git a/spring-mvc-java/src/main/resources/views.properties b/spring-mvc-java/src/main/resources/views.properties deleted file mode 100644 index 95687cb62a..0000000000 --- a/spring-mvc-java/src/main/resources/views.properties +++ /dev/null @@ -1,3 +0,0 @@ -sample.(class)=org.springframework.web.servlet.view.JstlView -sample.url=/WEB-INF/view/sample.jsp - diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp index 8a32fd12b6..268f0a055a 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -8,7 +8,7 @@

Welcome, Enter The Employee Details

- + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp index 627a9d9ddb..1457bc5fc8 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -6,7 +6,6 @@

Submitted Employee Information

-

${msg}

Name
@@ -20,10 +19,6 @@ - - - -
Name :Contact Number : ${contactNumber}
Working Area :${workingArea}
\ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9777addb61 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.config.AppInitializer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 529879fada..75efd57ae4 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -15,7 +15,7 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller.message" }) public class TestConfig implements WebMvcConfigurer { @Autowired @@ -44,5 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } - } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java deleted file mode 100644 index 0c2aa3de1b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -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.web.WebAppConfiguration; - -import com.baeldung.model.Employee; -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class EmployeeIntegrationTest { - - @Autowired - private EmployeeController employeeController; - - @Before - public void setup() { - employeeController.initEmployees(); - } - - @Test - public void whenInitEmployees_thenVerifyValuesInitiation() { - - Employee employee1 = employeeController.employeeMap.get(1L); - Employee employee2 = employeeController.employeeMap.get(2L); - Employee employee3 = employeeController.employeeMap.get(3L); - - Assert.assertTrue(employee1.getId() == 1L); - Assert.assertTrue(employee1.getName().equals("John")); - Assert.assertTrue(employee1.getContactNumber().equals("223334411")); - Assert.assertTrue(employee1.getWorkingArea().equals("rh")); - - Assert.assertTrue(employee2.getId() == 2L); - Assert.assertTrue(employee2.getName().equals("Peter")); - Assert.assertTrue(employee2.getContactNumber().equals("22001543")); - Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); - - Assert.assertTrue(employee3.getId() == 3L); - Assert.assertTrue(employee3.getName().equals("Mike")); - Assert.assertTrue(employee3.getContactNumber().equals("223334411")); - Assert.assertTrue(employee3.getWorkingArea().equals("admin")); - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java deleted file mode 100644 index fb21905027..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -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.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class RequestMapingShortcutsIntegrationTest { - - @Autowired - private WebApplicationContext ctx; - - private MockMvc mockMvc; - - @Before - public void setup () { - DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); - this.mockMvc = builder.build(); - } - - @Test - public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - -} diff --git a/spring-mvc-kotlin/.gitignore b/spring-mvc-kotlin/.gitignore new file mode 100644 index 0000000000..416395ffea --- /dev/null +++ b/spring-mvc-kotlin/.gitignore @@ -0,0 +1 @@ +transaction.log \ No newline at end of file diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md index e5167f69fc..cc6827eb1b 100644 --- a/spring-mvc-kotlin/README.md +++ b/spring-mvc-kotlin/README.md @@ -2,3 +2,4 @@ - [Spring MVC Setup with Kotlin](http://www.baeldung.com/spring-mvc-kotlin) - [Working with Kotlin and JPA](http://www.baeldung.com/kotlin-jpa) - [Kotlin-allopen and Spring](http://www.baeldung.com/kotlin-allopen-spring) +- [MockMvc Kotlin DSL](https://www.baeldung.com/mockmvc-kotlin-dsl) diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index fc76f58727..fb1f242644 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -15,12 +15,12 @@ - org.springframework - spring-web + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-webmvc + org.springframework.boot + spring-boot-starter-json org.thymeleaf @@ -46,8 +46,8 @@ test - org.springframework - spring-test + org.springframework.boot + spring-boot-starter-test test diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt new file mode 100644 index 0000000000..68ab5f31a6 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.mockmvc + +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/mockmvc") +class MockMvcController { + + @RequestMapping(value = ["/validate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) + fun validate(@RequestBody request: Request): Response { + val error = if (request.name.first == "admin") { + null + } else { + ERROR + } + return Response(error) + } + + companion object { + const val ERROR = "invalid user" + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt new file mode 100644 index 0000000000..3231b6f186 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt @@ -0,0 +1,10 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.annotation.JsonInclude + +data class Name(val first: String, val last: String) + +data class Request(val name: Name) + +@JsonInclude(JsonInclude.Include.NON_NULL) +data class Response(val error: String?) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt new file mode 100644 index 0000000000..802cd4c1e7 --- /dev/null +++ b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt @@ -0,0 +1,61 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity.status +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.post +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders +import org.springframework.test.web.servlet.result.MockMvcResultHandlers +import org.springframework.test.web.servlet.result.MockMvcResultMatchers + +@RunWith(SpringRunner::class) +@WebMvcTest +class MockMvcControllerTest { + + @Autowired lateinit var mockMvc: MockMvc + @Autowired lateinit var mapper: ObjectMapper + + @Test + fun `when supported user is given then raw MockMvc-based validation is successful`() { + mockMvc.perform(MockMvcRequestBuilders + .post("/mockmvc/validate") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(Request(Name("admin", ""))))) + .andExpect(MockMvcResultMatchers.status().isOk) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.content().string("{}")) + } + + @Test + fun `when supported user is given then kotlin DSL-based validation is successful`() { + doTest(Request(Name("admin", "")), Response(null)) + } + + @Test + fun `when unsupported user is given then validation is failed`() { + doTest(Request(Name("some-name", "some-surname")), Response(MockMvcController.ERROR)) + } + + private fun doTest(input: Request, expectation: Response) { + mockMvc.post("/mockmvc/validate") { + contentType = MediaType.APPLICATION_JSON + content = mapper.writeValueAsString(input) + accept = MediaType.APPLICATION_JSON + }.andExpect { + status { isOk } + content { contentType(MediaType.APPLICATION_JSON) } + content { json(mapper.writeValueAsString(expectation)) } + } + } +} + +@SpringBootApplication +class MockMvcApplication \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index a767cf3c37..580a40e50b 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -47,7 +47,7 @@ commons-fileupload commons-fileupload - ${fileupload.version} + ${commons-fileupload.version} org.springframework @@ -162,18 +162,16 @@ 1.8 1.8 - 3.2.0 2.21.0 2.3.2-b02 4.0.0 6.0.10.Final enter-location-of-server - 1.3.2 + 1.3.2 3.0.7.RELEASE 2.4.12 2.3.27-incubating 1.2.5 - 1.0.2 1.9.0 1.4.9 5.1.0 diff --git a/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab0b23c4a5 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.configuration.ApplicationConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes={ApplicationConfiguration.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} + diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index df19b67e8e..5954e48e8f 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -115,7 +115,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..22a4486aa7 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index c8de990da0..219a2be689 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -94,7 +94,6 @@ 4.5.2 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..122dc18bad --- /dev/null +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.WebFlowConfig; +import org.baeldung.spring.WebMvcConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {WebFlowConfig.class, WebMvcConfig.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 46af321d1b..9f7a24b358 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -33,7 +33,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -82,7 +82,7 @@ org.glassfish javax.el - 3.0.1-b08 + ${javax.el.version} @@ -129,18 +129,13 @@ 6.0.10.Final - 1.2 - 3.1.0 - 2.9.6 + 3.0.1-b08 19.0 - 3.5 - 2.5 2.8.0 - 2.6 1.6.1 diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..27dcb83bd4 --- /dev/null +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4f655277b7 --- /dev/null +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.protobuf.Application; + +@DirtiesContext +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 58e72c1d51..4c7ac6eee9 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -32,6 +32,16 @@ quartz ${quartz.version} + + com.mchange + c3p0 + ${c3p0.version} + + + + com.h2database + h2 +
@@ -44,7 +54,8 @@ - 2.2.3 + 2.3.0 + 0.9.5.2 \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index 6601df6c94..ccf9fca8c1 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -10,17 +10,20 @@ import javax.annotation.PostConstruct; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; -import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; +import java.util.Properties; + @Configuration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='false'") public class QrtzScheduler { @@ -45,14 +48,9 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { - - StdSchedulerFactory factory = new StdSchedulerFactory(); - factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); - + public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); - scheduler.setJobFactory(springBeanJobFactory()); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); @@ -60,6 +58,21 @@ public class QrtzScheduler { return scheduler; } + @Bean + public SchedulerFactoryBean schedulerFactoryBean() throws IOException { + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setJobFactory(springBeanJobFactory()); + factory.setQuartzProperties(quartzProperties()); + return factory; + } + + public Properties quartzProperties() throws IOException { + PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); + propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); + propertiesFactoryBean.afterPropertiesSet(); + return propertiesFactoryBean.getObject(); + } + @Bean public JobDetail jobDetail() { diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index 9978f61522..f824765efe 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,6 +1,7 @@ package org.baeldung.springquartz.basics.scheduler; import javax.annotation.PostConstruct; +import javax.sql.DataSource; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.JobDetail; @@ -9,7 +10,11 @@ import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.quartz.QuartzDataSource; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,6 +25,7 @@ import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; @Configuration +@EnableAutoConfiguration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='true'") public class SpringQrtzScheduler { @@ -43,7 +49,7 @@ public class SpringQrtzScheduler { } @Bean - public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job) { + public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource quartzDataSource) { SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties")); @@ -53,6 +59,9 @@ public class SpringQrtzScheduler { schedulerFactory.setJobDetails(job); schedulerFactory.setTriggers(trigger); + // Comment the following line to use the default Quartz job store. + schedulerFactory.setDataSource(quartzDataSource); + return schedulerFactory; } @@ -81,4 +90,12 @@ public class SpringQrtzScheduler { trigger.setName("Qrtz_Trigger"); return trigger; } + + @Bean + @QuartzDataSource + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource quartzDataSource() { + return DataSourceBuilder.create().build(); + } + } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java index ddf4efc2c5..6f66352616 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java @@ -4,20 +4,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.concurrent.atomic.AtomicInteger; + @Service public class SampleJobService { + public static final long EXECUTION_TIME = 5000L; + private Logger logger = LoggerFactory.getLogger(getClass()); + private AtomicInteger count = new AtomicInteger(); + public void executeSampleJob() { logger.info("The sample job has begun..."); try { - Thread.sleep(5000); + Thread.sleep(EXECUTION_TIME); } catch (InterruptedException e) { logger.error("Error while executing sample job", e); } finally { + count.incrementAndGet(); logger.info("Sample job has finished..."); } } + + public int getNumberOfInvocations() { + return count.get(); + } } diff --git a/spring-quartz/src/main/resources/application.properties b/spring-quartz/src/main/resources/application.properties index 7bdd647e25..557349af2e 100644 --- a/spring-quartz/src/main/resources/application.properties +++ b/spring-quartz/src/main/resources/application.properties @@ -1 +1,10 @@ -using.spring.schedulerFactory=true \ No newline at end of file +using.spring.schedulerFactory=true + +spring.quartz.job-store-type=jdbc +# Always create the Quartz database on startup +spring.quartz.jdbc.initialize-schema=always + +spring.datasource.jdbc-url=jdbc:h2:mem:spring-quartz;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= diff --git a/spring-quartz/src/main/resources/quartz.properties b/spring-quartz/src/main/resources/quartz.properties index cefaaef8e4..662bb83eb0 100644 --- a/spring-quartz/src/main/resources/quartz.properties +++ b/spring-quartz/src/main/resources/quartz.properties @@ -4,7 +4,19 @@ org.quartz.threadPool.threadCount=2 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true # job-store -org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore +# Enable this property for RAMJobStore +#org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore -# others -org.quartz.jobStore.misfireThreshold = 60000 \ No newline at end of file +# Enable these properties for a JDBCJobStore using JobStoreTX +org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX +org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +org.quartz.jobStore.dataSource=quartzDataSource +# Enable this property for JobStoreCMT +#org.quartz.jobStore.nonManagedTXDataSource=quartzDataSource + +# H2 database +# use an in-memory database & initialise Quartz using their standard SQL script +org.quartz.dataSource.quartzDataSource.URL=jdbc:h2:mem:spring-quartz;INIT=RUNSCRIPT FROM 'classpath:/org/quartz/impl/jdbcjobstore/tables_h2.sql' +org.quartz.dataSource.quartzDataSource.driver=org.h2.Driver +org.quartz.dataSource.quartzDataSource.user=sa +org.quartz.dataSource.quartzDataSource.password= diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 516cc587a7..fec47f045c 100644 --- a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,30 @@ package org.baeldung; import org.baeldung.springquartz.SpringQuartzApp; +import org.baeldung.springquartz.basics.service.SampleJobService; 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.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringQuartzApp.class) public class SpringContextIntegrationTest { + @Autowired + private SampleJobService sampleJobService; + @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } + + @Test + public void whenSchedulerStarts_thenJobsRun() throws InterruptedException { + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(0); + Thread.sleep(SampleJobService.EXECUTION_TIME); + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(1); + } } diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a210e847c8 --- /dev/null +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springquartz.SpringQuartzApp; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringQuartzApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fe20382ab4 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.AmqpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpClient.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4325b0ddef --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.BurlapClient; +import com.baeldung.client.HessianClient; + +@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95721b6eaa --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.JmsClient; + +@SpringBootTest(classes = JmsClient.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6cae1b66fc --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.RmiServer; + +@SpringBootTest(classes = RmiServer.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 5240ae24e7..69becfb4ae 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -74,7 +74,6 @@ 19.0 - 3.5 org.baeldung.web.main.Application diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9136ce43eb --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.web.main.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index a85393b7a8..5bc3a70ed5 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -287,7 +287,6 @@ 19.0 - 3.5 3.25.0-GA diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8debddc40a --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 70fea91f31..7ee658d8ba 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -353,7 +353,6 @@ 19.0 - 3.5 1.7.0 diff --git a/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..57886a232a --- /dev/null +++ b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 882d0ac301..c01f27bd98 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -5,3 +5,4 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) +- [CORS with Spring](https://www.baeldung.com/spring-cors) diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index d301957eb9..263e451c62 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -323,7 +323,6 @@ 4.0.0 1.4 3.1.0 - 3.5 1.4.9 diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java b/spring-rest-simple/src/main/java/com/baeldung/Application.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/config/Application.java rename to spring-rest-simple/src/main/java/com/baeldung/Application.java index 5c9a186619..dc6bfcb970 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java +++ b/spring-rest-simple/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,8 +7,8 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration -@ComponentScan("org.baeldung") @SpringBootApplication +@ComponentScan("com.baeldung.cors") public class Application extends SpringBootServletInitializer { public static void main(final String[] args) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java similarity index 86% rename from spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java index 191b87a8f2..d169f7e9d4 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java @@ -1,6 +1,5 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -13,9 +12,12 @@ import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConve import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.config.converter.KryoHttpMessageConverter; + import java.text.SimpleDateFormat; import java.util.List; @@ -24,10 +26,10 @@ import java.util.List; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) -public class WebConfig implements WebMvcConfigurer { +@ComponentScan({ "com.baeldung.web" }) +public class MvcConfig implements WebMvcConfigurer { - public WebConfig() { + public MvcConfig() { super(); } @@ -64,4 +66,10 @@ public class WebConfig implements WebMvcConfigurer { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } + + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } } diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java rename to spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java index 6af54c379a..7ab8282350 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java @@ -1,13 +1,13 @@ -package org.baeldung.config.converter; +package com.baeldung.config.converter; import java.io.IOException; -import org.baeldung.web.dto.Foo; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; +import com.baeldung.web.dto.Foo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java new file mode 100644 index 0000000000..429b0c102e --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java @@ -0,0 +1,18 @@ +package com.baeldung.cors; + +public class Account { + private Long id; + + public Account(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java new file mode 100644 index 0000000000..c387eb2121 --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java @@ -0,0 +1,24 @@ +package com.baeldung.cors; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@CrossOrigin(maxAge = 3600) +@RestController +@RequestMapping("/account") +public class AccountController { + + @CrossOrigin("http://example.com") + @RequestMapping("/{id}") + public Account retrieve(@PathVariable Long id) { + return new Account(id); + } + + @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") + public void remove(@PathVariable Long id) { + // ... + } +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java similarity index 97% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java index 1c3a1086ca..3611a4e6cc 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java index 4bcafc04fc..6c7da0296f 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.Arrays; import java.util.List; -import org.baeldung.web.dto.Bazz; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -15,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.web.dto.Bazz; import com.fasterxml.jackson.core.JsonProcessingException; @RestController diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java index c68d586667..bab315c027 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java @@ -1,11 +1,9 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.List; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -16,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; import com.google.common.collect.Lists; @Controller diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java similarity index 98% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java index 5fb92d6d87..ec75e4c859 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java similarity index 94% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java index ceda138768..0cc657f0f2 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java similarity index 88% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java index 458bdaf170..301a25d070 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java similarity index 91% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java index d9a495b726..861b4009b5 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; public class Bazz { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java index 240b368b50..5a54539927 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java index 8ca96c38fc..db7cb66f87 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java @@ -1,7 +1,7 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: FooProtos.proto -package org.baeldung.web.dto; +package com.baeldung.web.dto; public final class FooProtos { private FooProtos() { @@ -115,11 +115,11 @@ public final class FooProtos { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @@ -255,43 +255,43 @@ public final class FooProtos { return super.writeReplace(); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } @@ -303,7 +303,7 @@ public final class FooProtos { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + public static Builder newBuilder(com.baeldung.web.dto.FooProtos.Foo prototype) { return newBuilder().mergeFrom(prototype); } @@ -322,13 +322,13 @@ public final class FooProtos { */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { + com.baeldung.web.dto.FooProtos.FooOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() @@ -364,23 +364,23 @@ public final class FooProtos { } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + public com.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); } - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + public com.baeldung.web.dto.FooProtos.Foo build() { + com.baeldung.web.dto.FooProtos.Foo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + public com.baeldung.web.dto.FooProtos.Foo buildPartial() { + com.baeldung.web.dto.FooProtos.Foo result = new com.baeldung.web.dto.FooProtos.Foo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { @@ -397,16 +397,16 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + if (other instanceof com.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((com.baeldung.web.dto.FooProtos.Foo) other); } else { super.mergeFrom(other); return this; } } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + public Builder mergeFrom(com.baeldung.web.dto.FooProtos.Foo other) { + if (other == com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; if (other.hasId()) { setId(other.getId()); @@ -433,11 +433,11 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + com.baeldung.web.dto.FooProtos.Foo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + parsedMessage = (com.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java rename to spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java index b2137aeeff..3ebba8ae1c 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import javax.servlet.http.HttpServletResponse; diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 0000000000..e83e13be71 --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..b66e642b80 --- /dev/null +++ b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 66% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java index 66ffe4947d..4bbfa2818e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class TestConfig { } diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 92% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index 7f78146b84..d1ae7f65c6 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -1,9 +1,7 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,8 +14,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.MvcConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class ExampleControllerIntegrationTest { diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java similarity index 96% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index dfb3ff7a38..4f0395e914 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -1,5 +1,5 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -9,8 +9,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,9 +21,11 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.MvcConfig; + @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class BazzNewMappingsExampleIntegrationTest { diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java index 9dd6b13f18..f26f241beb 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java index e213d0255f..51e3fb097e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.equalTo; @@ -13,7 +13,6 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -31,6 +30,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; +import com.baeldung.web.dto.Foo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java similarity index 96% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java index 7f250653ab..c6929da818 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java @@ -1,13 +1,10 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.Arrays; -import org.baeldung.config.converter.KryoHttpMessageConverter; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -18,6 +15,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.web.client.RestTemplate; +import com.baeldung.config.converter.KryoHttpMessageConverter; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; + /** * Integration Test class. Tests methods hits the server's rest services. */ diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java index b920ed38da..49ac651da2 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java similarity index 98% rename from spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java rename to spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..86b35d2b4e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import java.util.List; diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest/README.md b/spring-rest/README.md index 5d7894cdf8..54b47604d4 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -6,7 +6,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) -- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 36934af101..670bac9805 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -93,13 +93,6 @@ commons-lang3
- - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - org.hamcrest @@ -270,7 +263,6 @@ 4.0.0 1.4 3.1.0 - 3.5 20.0 @@ -280,8 +272,6 @@ 3.0.4 3.0.0 false - - 3.4.1 2.2.0 3.5.11 diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4b2024e207 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.custom.CustomApplication; +import com.baeldung.produceimage.ImageApplication; +import com.baeldung.propertyeditor.PropertyEditorApplication; +import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.sampleapp.config.MainApplication; +import com.baeldung.web.log.app.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class, + MainApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index c2c4965231..97a89ff7aa 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) +- [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 06d4eed9fc..ae5cfed4c9 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -284,7 +284,6 @@ - 3.5 1.4.9 diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e52d249f0b --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.resttemplate.RestTemplateConfigurationApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RestTemplateConfigurationApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index a54c124d5f..ff3034a50d 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -188,7 +188,7 @@ public class RestTemplateBasicLiveTest { final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity requestUpdate = new HttpEntity<>(updatedResource, headers); - final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); + final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); @@ -262,7 +262,7 @@ public class RestTemplateBasicLiveTest { // Simply setting restTemplate timeout using ClientHttpRequestFactory - ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + ClientHttpRequestFactory getClientHttpRequestFactory() { final int timeout = 5; final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setConnectTimeout(timeout * 1000); diff --git a/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..74f26e2e5a --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.acl.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-angular/README.md b/spring-security-angular/README.md index 49cd8dd62d..80312c4bab 100644 --- a/spring-security-angular/README.md +++ b/spring-security-angular/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) -- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) diff --git a/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e61d512bca --- /dev/null +++ b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootSecurityApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8fbaa7169b --- /dev/null +++ b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.cachecontrol.AppRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AppRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java similarity index 90% rename from spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java index 66243ef00d..0afb3899db 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) -public class SpringContextIntegrationTest { +public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1707c706ae --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.app.App; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = App.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java index 309ee3076d..009d9af9fc 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java @@ -80,7 +80,7 @@ public class TestMethodSecurity { @Test @WithMockUser(username = "JOHN", authorities = { "SYS_ADMIN" }) - public void givenAuthoritySysAdmin_whenCallGetUsernameInLowerCase_thenReturnUsername() { + public void givenAuthoritySysAdmin_whenCallGetUsernameLC_thenReturnUsername() { String username = userRoleService.getUsernameLC(); assertEquals("john", username); } diff --git a/spring-security-kerberos/pom.xml b/spring-security-kerberos/pom.xml index 35c4ba4926..d98d0ff508 100644 --- a/spring-security-kerberos/pom.xml +++ b/spring-security-kerberos/pom.xml @@ -7,12 +7,14 @@ 0.1-SNAPSHOT spring-security-kerberos war + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-1 + org.springframework.boot @@ -50,6 +52,7 @@ test + diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java index f2da5af92c..739e4d3417 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java @@ -1,57 +1,12 @@ package org.baeldung.custom.config; -import org.baeldung.custom.security.MyUserDetailsService; -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.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration -@EnableWebSecurity -@ComponentScan("org.baeldung.security") -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private MyUserDetailsService userDetailsService; - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider()); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() - .antMatchers("/admin").hasRole("ADMIN") - .anyRequest().authenticated() - .and().formLogin().permitAll() - .and().csrf().disable(); - ; - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(userDetailsService); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } +public class SecurityConfig { @Bean public PasswordEncoder encoder() { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java index 6572954427..74de45d1a8 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java @@ -3,14 +3,16 @@ package org.baeldung.custom.web; import org.baeldung.custom.persistence.dao.OrganizationRepository; import org.baeldung.custom.persistence.model.Foo; import org.baeldung.custom.persistence.model.Organization; +import org.baeldung.custom.security.MyUserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @@ -23,14 +25,14 @@ public class MainController { // @PostAuthorize("hasPermission(returnObject, 'read')") @PreAuthorize("hasPermission(#id, 'Foo', 'read')") - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @GetMapping("/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo("Sample"); } @PreAuthorize("hasPermission(#foo, 'write')") - @RequestMapping(method = RequestMethod.POST, value = "/foos") + @PostMapping("/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { @@ -40,7 +42,7 @@ public class MainController { // @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") - @RequestMapping(method = RequestMethod.GET, value = "/foos") + @GetMapping("/foos") @ResponseBody public Foo findFooByName(@RequestParam final String name) { return new Foo(name); @@ -49,10 +51,18 @@ public class MainController { // @PreAuthorize("isMember(#id)") - @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") + @GetMapping("/organizations/{id}") @ResponseBody public Organization findOrgById(@PathVariable final long id) { - return organizationRepository.findById(id).orElse(null); + return organizationRepository.findById(id) + .orElse(null); + } + + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") + @GetMapping("/user") + @ResponseBody + public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { + return principal; } } diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2041249b71 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.custom.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java index fb25175902..d16acc729a 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,76 +1,89 @@ package org.baeldung.web; -import static org.junit.Assert.assertEquals; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.apache.http.HttpHeaders; import org.baeldung.custom.Application; -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.SecurityConfig; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.baeldung.custom.persistence.model.Foo; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.security.test.context.support.WithUserDetails; +import org.springframework.test.web.servlet.MockMvc; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {Application.class}) -@WebAppConfiguration +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest(classes = { Application.class }) +@AutoConfigureMockMvc public class CustomUserDetailsServiceIntegrationTest { - private static final String USERNAME = "user"; - private static final String PASSWORD = "pass"; - private static final String USERNAME2 = "user2"; - @Autowired - private UserRepository myUserRepository; - - @Autowired - private AuthenticationProvider authenticationProvider; - - @Autowired - private PasswordEncoder passwordEncoder; - - // + private MockMvc mvc; @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges[0].name").value("FOO_READ_PRIVILEGE")) + .andExpect(jsonPath("$.user.organization.name").value("FirstOrg")) + .andExpect(jsonPath("$.user.username").value("john")); } - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - authenticationProvider.authenticate(auth); + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges").isArray()) + .andExpect(jsonPath("$.user.organization.name").value("SecondOrg")) + .andExpect(jsonPath("$.user.username").value("tom")); } - // + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestFoo_thenRetrieveSampleFoo() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value("Sample")); + } - @After - public void tearDown() { - myUserRepository.removeUserByUsername(USERNAME); + @Test + @WithAnonymousUser + public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenCreateNewFoo_thenForbiddenStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isForbidden()); + } + + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenCreateNewFoo_thenOkStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isCreated()); + } + + private static String asJsonString(final Object obj) throws Exception { + final ObjectMapper mapper = new ObjectMapper(); + final String jsonContent = mapper.writeValueAsString(obj); + return jsonContent; } } diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 4e932f3245..3bae514bc1 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -194,10 +194,8 @@ 19.0 - 3.5 - 2.6 1.6.1 diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index cf1de1730d..0baaea15ef 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -196,13 +196,11 @@ 19.0 - 3.5 4.4.5 4.5.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cd2b796308 --- /dev/null +++ b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientConfig; +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-jsonview/pom.xml b/spring-security-mvc-jsonview/pom.xml index 8fa7b4ffb5..a7f668ae8b 100644 --- a/spring-security-mvc-jsonview/pom.xml +++ b/spring-security-mvc-jsonview/pom.xml @@ -111,7 +111,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -206,12 +206,6 @@ - - 3.1.0 - 1.2 - - - 2.6 1.6.1 2.4.0 diff --git a/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b1a3de714e --- /dev/null +++ b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.AppConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..30ba7671d8 --- /dev/null +++ b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleLDAPApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 02ed0e36f2..1ca11bc1ab 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -175,7 +175,6 @@ - 2.6 1.6.1 diff --git a/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4cf3b736ea --- /dev/null +++ b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 5e987dcb77..2f7989d573 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -99,7 +99,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -200,15 +200,10 @@ 9.4.1212 - - 3.1.0 - 1.2 - 19.0 - 2.6 1.6.1 1.5.10.RELEASE diff --git a/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8113ed0fbe --- /dev/null +++ b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c0e1527a24..b55ce70517 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -8,10 +8,10 @@ war - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -19,74 +19,26 @@ - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} + org.springframework.boot + spring-boot-starter-security org.springframework.security spring-security-taglibs - ${org.springframework.security.version} - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-context - ${spring.version} + org.apache.tomcat.embed + tomcat-embed-jasper - org.springframework - spring-jdbc - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-tomcat @@ -94,14 +46,12 @@ javax.servlet javax.servlet-api - ${javax.servlet-api.version} provided javax.servlet jstl - ${jstl.version} runtime @@ -117,7 +67,6 @@ org.springframework.boot spring-boot-starter-test - 1.5.10.RELEASE test @@ -166,14 +115,10 @@ - - 4.2.6.RELEASE - 3.0.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java new file mode 100644 index 0000000000..9e52f0430a --- /dev/null +++ b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSessionApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSessionApplication.class, args); + } +} diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java index 9e9c240181..b9f50ded73 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java @@ -5,13 +5,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,7 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/anonymous.html"); diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index deeea78e4e..b7996ebf18 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -8,6 +8,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -24,9 +26,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() - .withUser("user1").password("user1Pass").roles("USER") + .withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER") .and() - .withUser("admin1").password("admin1Pass").roles("ADMIN"); + .withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN"); // @formatter:on } @@ -68,5 +70,10 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml index e8aa2f76bc..42ff4c2186 100644 --- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index f1d28355fd..f799a7fa9f 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -78,7 +78,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -186,7 +186,6 @@ 5.2.10.Final 4.2.3.RELEASE 1.11.3.RELEASE - 1.4.196 1.2.3 diff --git a/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b9c738904 --- /dev/null +++ b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springsecuredsockets.config.AppConfig; +import com.baeldung.springsecuredsockets.config.DataStoreConfig; +import com.baeldung.springsecuredsockets.config.SecurityConfig; +import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; +import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, + SocketBrokerConfig.class, SocketSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fa346b2b31 --- /dev/null +++ b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.SpringOpenidApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringOpenidApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index c7b7c85be8..40c284af7f 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -169,10 +169,8 @@ 19.0 - 3.5 - 2.6 2.7 1.6 9.4.11.v20180605 diff --git a/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cc52b4726 --- /dev/null +++ b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 8a90247386..78bab83db5 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -279,7 +279,6 @@ 19.0 - 2.6 1.6.1 diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f54cbf3b7b --- /dev/null +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/webSecurityConfig.xml" }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 2180b917e5..4bab9b9d95 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -206,7 +206,6 @@ 19.0 - 3.5 1.2 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index af38c1ffef..a66909a68e 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -271,7 +271,6 @@ 26.0-jre - 3.5 1.3.2 diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java new file mode 100644 index 0000000000..7d40b9bb8d --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java @@ -0,0 +1,14 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class CustomController { + + @RequestMapping(value = "/custom", method = RequestMethod.POST) + public String custom() { + return "custom"; + } +} \ No newline at end of file diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d984cf5c35 --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f677f683b2 --- /dev/null +++ b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.AuthorizationServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/README.md b/spring-session/README.md index 505d043e75..c9875beadf 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) +- [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b69855ba38 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springsessionjdbc.SpringSessionJdbcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionJdbcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml index 16fbaccc84..dc055ff32d 100644 --- a/spring-session/spring-session-mongodb/pom.xml +++ b/spring-session/spring-session-mongodb/pom.xml @@ -42,11 +42,6 @@
- - 2.1.3.RELEASE - 2.1.5.RELEASE - - @@ -56,4 +51,9 @@ + + 2.1.3.RELEASE + 2.1.5.RELEASE + + \ No newline at end of file diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..307d31a809 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionMongoDBApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..994f93c24f --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SessionWebApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff22398ca4 --- /dev/null +++ b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SleuthWebApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SleuthWebApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index ba05eddf5d..e155a0f6b2 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -13,11 +13,6 @@ ../parent-boot-2 - - 1.8 - 2.1.2.RELEASE - - @@ -66,4 +61,8 @@ + + 2.1.2.RELEASE + + diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index e948c908d4..655e885568 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -94,8 +94,4 @@ - - 3.3.2 - - \ No newline at end of file diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cfd8759c52 --- /dev/null +++ b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e25c1bf8e4 --- /dev/null +++ b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1e847c0d65 --- /dev/null +++ b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,23 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, + JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, + ForkJoinStateMachineConfiguration.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-static-resources/README.md b/spring-static-resources/README.md index c12e0272d4..64f017b5dd 100644 --- a/spring-static-resources/README.md +++ b/spring-static-resources/README.md @@ -2,3 +2,4 @@ - [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc) - [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets) - [Serve Static Resources with Spring](http://www.baeldung.com/spring-mvc-static-resources) +- [Load a Resource as a String in Spring](https://www.baeldung.com/spring-load-resource-as-string) diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index 84519a37c1..b8068814ba 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -145,7 +145,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} @@ -215,9 +215,6 @@ 1.5.1 - - - 2.5 \ No newline at end of file diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0dcbba3221 --- /dev/null +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecSecurityConfig.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79b2b7fa88 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.petstore.app.PetStoreApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PetStoreApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-thymeleaf-2/pom.xml b/spring-thymeleaf-2/pom.xml index bc1147cb14..1b95cac43c 100644 --- a/spring-thymeleaf-2/pom.xml +++ b/spring-thymeleaf-2/pom.xml @@ -23,11 +23,6 @@ - - 1.8 - 1.8 - - @@ -37,4 +32,9 @@ spring-thymeleaf-2 + + + 1.8 + 1.8 + diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java new file mode 100644 index 0000000000..2fd11628ad --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.thymeleaf; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +@Configuration +public class ThymeleafConfig { + + @Bean + public ClassLoaderTemplateResolver secondaryTemplateResolver() { + ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); + secondaryTemplateResolver.setPrefix("templates-2/"); + secondaryTemplateResolver.setSuffix(".html"); + secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); + secondaryTemplateResolver.setCharacterEncoding("UTF-8"); + secondaryTemplateResolver.setOrder(1); + secondaryTemplateResolver.setCheckExistence(true); + + return secondaryTemplateResolver; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java new file mode 100644 index 0000000000..b404418106 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf.templatedir; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HelloController { + + @GetMapping("/hello") + public String sayHello() { + return "hello"; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/application.properties b/spring-thymeleaf-2/src/main/resources/application.properties new file mode 100644 index 0000000000..b09232bb1b --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/application.properties @@ -0,0 +1 @@ +#spring.thymeleaf.prefix=classpath:/templates-2/ \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates-2/hello.html b/spring-thymeleaf-2/src/main/resources/templates-2/hello.html new file mode 100644 index 0000000000..035904c8ba --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates-2/hello.html @@ -0,0 +1,10 @@ + + + + +Enums in Thymeleaf + + +

Hello from 'templates/templates-2'

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1ff1c52c68 --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,22 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-userservice/.springBeans b/spring-userservice/.springBeans deleted file mode 100644 index ff32b84d3b..0000000000 --- a/spring-userservice/.springBeans +++ /dev/null @@ -1,15 +0,0 @@ - - - 1 - - - - - - - - - - - - diff --git a/spring-userservice/README.md b/spring-userservice/README.md deleted file mode 100644 index 097afc5fc1..0000000000 --- a/spring-userservice/README.md +++ /dev/null @@ -1 +0,0 @@ -spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml deleted file mode 100644 index e6e8553c80..0000000000 --- a/spring-userservice/pom.xml +++ /dev/null @@ -1,244 +0,0 @@ - - 4.0.0 - spring-userservice - spring-userservice - 0.0.1-SNAPSHOT - war - spring-userservice - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - - - - org.springframework - spring-orm - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - org.hibernate - hibernate-ehcache - ${hibernate.version} - - - xml-apis - xml-apis - ${xml-apis.version} - - - org.javassist - javassist - ${javassist.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.hibernate - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - org.springframework - spring-test - ${spring.version} - test - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.springframework.security - spring-security-core - ${org.springframework.security.version} - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - - org.apache.derby - derby - ${derby.version} - - - org.apache.derby - derbyclient - ${derby.version} - - - org.apache.derby - derbynet - ${derby.version} - - - org.apache.derby - derbytools - ${derby.version} - - - taglibs - standard - ${taglibs-standard.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl.version} - - - org.springframework.boot - spring-boot-test - ${spring-boot.version} - - - org.springframework.boot - spring-boot - ${spring-boot.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - - - spring-userservice - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - - - - - 4.2.6.RELEASE - 1.5.14.RELEASE - 3.21.0-GA - - - 5.2.10.Final - 5.1.40 - 1.10.5.RELEASE - 10.13.1.1 - - - 5.3.3.Final - 2.2.5 - 1.1.2 - - - 19.0 - 3.5 - 1.4.01 - - - 2.6 - - - \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java deleted file mode 100644 index 4a9e737a92..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.custom.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = { "org.baeldung.security" }) -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/"); - registry.addViewController("/index"); - registry.addViewController("/login"); - registry.addViewController("/register"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java deleted file mode 100644 index 6be7053b78..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.custom.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -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.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -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 com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-derby.properties" }) -public class PersistenceDerbyJPAConfig { - - @Autowired - private Environment env; - - public PersistenceDerbyJPAConfig() { - super(); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean myEmf() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter 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 JpaTransactionManager transactionManager = new JpaTransactionManager(); - 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", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - - @Bean - public MyUserDAO myUserDAO() { - final MyUserDAO myUserDAO = new MyUserDAO(); - return myUserDAO; - } -} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java deleted file mode 100644 index 44df02980f..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.custom.config; - -import org.baeldung.security.MyUserDetailsService; -import org.baeldung.user.service.MyUserService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -@EnableWebSecurity -@Profile("!https") -public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - - public SecSecurityConfig() { - super(); - } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.authenticationProvider(authenticationProvider()); - // @formatter:on - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/*").permitAll() - .and() - .formLogin() - .loginPage("/login") - .loginProcessingUrl("/login") - .defaultSuccessUrl("/",true) - .failureUrl("/login?error=true") - .and() - .logout() - .logoutUrl("/logout") - .deleteCookies("JSESSIONID") - .logoutSuccessUrl("/"); - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(myUserDetailsService()); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - - @Bean - public MyUserDetailsService myUserDetailsService() { - return new MyUserDetailsService(); - } - - @Bean - public MyUserService myUserService() { - return new MyUserService(); - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java deleted file mode 100644 index 804d391641..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "spring_custom_user_service") -public class MyUser { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(unique = true, nullable = false) - private String username; - - @Column(nullable = false) - private String password; - - public MyUser() { - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java deleted file mode 100644 index fe97984af8..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.security; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service("userDetailsService") -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - MyUserDAO myUserDAO; - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - final MyUser user = myUserDAO.findByUsername(username); - - if (user == null) { - throw new UsernameNotFoundException("No user found with username: " + username); - } - return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); - - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java deleted file mode 100644 index a4c15f7942..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/UserController.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.baeldung.security; - -import javax.annotation.Resource; - -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -public class UserController { - - @Resource - MyUserService myUserService; - - @RequestMapping(value = "/register", method = RequestMethod.POST) - public String registerUserAccount(final MyUserDto accountDto, final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - try { - myUserService.registerNewUserAccount(accountDto); - model.addAttribute("message", "Registration successful"); - return "index"; - } catch (final Exception exc) { - model.addAttribute("message", "Registration failed"); - - return "index"; - } - } - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String getHomepage(final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - return "index"; - } - - @RequestMapping(value = "/register", method = RequestMethod.GET) - public String getRegister() { - return "register"; - } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String getLogin() { - return "login"; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java deleted file mode 100644 index 834941b68b..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.user.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.baeldung.persistence.model.MyUser; -import org.springframework.stereotype.Repository; - -@Repository -public class MyUserDAO { - - @PersistenceContext - private EntityManager entityManager; - - public MyUser findByUsername(final String username) { - final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); - query.setParameter("username", username); - final List result = query.getResultList(); - if (result != null && result.size() > 0) { - return result.get(0); - } else - return null; - } - - public MyUser save(final MyUser user) { - entityManager.persist(user); - return user; - } - - public void removeUserByUsername(String username) { - final Query query = entityManager.createQuery("delete from MyUser where username=:username"); - query.setParameter("username", username); - query.executeUpdate(); - } - - public EntityManager getEntityManager() { - return entityManager; - } - - public void setEntityManager(final EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java deleted file mode 100644 index 2ab44752c0..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.user.service; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.baeldung.web.MyUserDto; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class MyUserService { - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - MyUserDAO myUserDAO; - - public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { - if (usernameExists(accountDto.getUsername())) { - throw new Exception("There is an account with that username: " + accountDto.getUsername()); - } - final MyUser user = new MyUser(); - - user.setUsername(accountDto.getUsername()); - user.setPassword(passwordEncoder.encode(accountDto.getPassword())); - return myUserDAO.save(user); - } - - public MyUser getUserByUsername(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - return user; - } - - public void removeUserByUsername(String username) { - myUserDAO.removeUserByUsername(username); - } - - private boolean usernameExists(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - if (user != null) { - return true; - } - return false; - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java deleted file mode 100644 index 60a6848ea4..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -public class MyUserDto { - @NotNull - @Size(min = 1) - private String username; - - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - -} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties deleted file mode 100644 index b76c5de12f..0000000000 --- a/spring-userservice/src/main/resources/persistence-derby.properties +++ /dev/null @@ -1,12 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver -jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true -jdbc.user=tutorialuser -jdbc.pass=tutorialpass - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.DerbyDialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=update -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c0..0000000000 --- a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml deleted file mode 100644 index 48ef8a8c43..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /WEB-INF/views/ - - - .jsp - - - - - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} - - - - - - - - - - - - - - - - - - - diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp deleted file mode 100644 index 0c89257cd2..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp +++ /dev/null @@ -1,35 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - - -Welcome! - - - - - - - -Register -

- -Login - -

-${message } -

- -Hello, ${name }! -
-
-Logout -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp deleted file mode 100644 index 29431f426d..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - - -

Login

- -
- - - - - - - - - - - - - -
User:
Password:
- -
- Username or password invalid! - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp deleted file mode 100644 index e6e9d373a0..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - -Welcome! - - - - - -Register here:

-
-Username:
-Password:
- -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b526774179..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - Spring MVC Application - - - - - - mvc-dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc-dispatcher - / - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - index.jsp - - - \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java similarity index 92% rename from spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-userservice/src/test/java/org/baeldung/SpringContextTest.java index 825b89eb10..2853a955fa 100644 --- a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -public class SpringContextIntegrationTest { +public class SpringContextTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java deleted file mode 100644 index 1cd38228b8..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.baeldung.userservice; - -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -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.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class CustomUserDetailsServiceIntegrationTest { - - private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); - - public static final String USERNAME = "user"; - public static final String PASSWORD = "pass"; - public static final String USERNAME2 = "user2"; - - @Autowired - MyUserService myUserService; - - @Autowired - AuthenticationProvider authenticationProvider; - - @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - myUserService.registerNewUserAccount(userDTO); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); - - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - try { - myUserService.registerNewUserAccount(userDTO); - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - -} diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95abe622fa --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springvault.SpringVaultApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringVaultApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4ce94ec16a --- /dev/null +++ b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.vertxspring.VertxSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VertxSpringApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..88d29d5ac0 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.amqp.SpringWebfluxAmqpApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringWebfluxAmqpApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index fbbbdddbf7..a613f51c3f 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -39,10 +39,6 @@ 2.1.0.RELEASE - - 3.5 - - 2.6 \ No newline at end of file diff --git a/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2a57d7aa07 --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.ResourceServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResourceServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fd35ec0841 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/struts-2/pom.xml b/struts-2/pom.xml index 7de688ff2c..1f7d6876d5 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -70,7 +70,6 @@ 2.5.5 2.5.8 4.3.6.RELEASE - 3.0.0 \ No newline at end of file diff --git a/tensorflow-java/pom.xml b/tensorflow-java/pom.xml index f9abde737c..84d2f6cf21 100644 --- a/tensorflow-java/pom.xml +++ b/tensorflow-java/pom.xml @@ -24,13 +24,13 @@ org.junit.jupiter junit-jupiter-api - ${junit.jupiter.version} + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -46,6 +46,5 @@ 1.12.0 - 5.4.0 \ No newline at end of file diff --git a/testing-modules/README.md b/testing-modules/README.md index d69f07215e..b269f547ec 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -13,5 +13,3 @@ - [Headers, Cookies and Parameters with REST-assured](http://www.baeldung.com/rest-assured-header-cookie-parameter) - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) -- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) -- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) diff --git a/easy-random/pom.xml b/testing-modules/easy-random/pom.xml similarity index 94% rename from easy-random/pom.xml rename to testing-modules/easy-random/pom.xml index 61f0ed2cd4..93c0027f8f 100644 --- a/easy-random/pom.xml +++ b/testing-modules/easy-random/pom.xml @@ -10,6 +10,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../../ diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Department.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Person.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java diff --git a/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java b/testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java similarity index 100% rename from easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java rename to testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java diff --git a/testing-modules/easymock/pom.xml b/testing-modules/easymock/pom.xml new file mode 100644 index 0000000000..ed9a077f67 --- /dev/null +++ b/testing-modules/easymock/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + easymock + easymock + http://maven.apache.org + + + com.baeldung + testing-modules + 1.0.0-SNAPSHOT + + + + + org.easymock + easymock + ${easymock.version} + test + + + + + UTF-8 + 4.0.2 + + diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java new file mode 100644 index 0000000000..482e985e5b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java @@ -0,0 +1,28 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class ForecastProcessor { + private WeatherService weatherService; + + public BigDecimal getMaximumTemperature(String locationName) { + + Location location = new Location(locationName); + + try { + weatherService.populateTemperature(location); + } catch (ServiceUnavailableException e) { + return null; + } + + return location.getMaximumTemparature(); + } + + public WeatherService getWeatherService() { + return weatherService; + } + + public void setWeatherService(WeatherService weatherService) { + this.weatherService = weatherService; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java new file mode 100644 index 0000000000..5f318acd5c --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java @@ -0,0 +1,33 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class Location { + private String name; + private BigDecimal minimumTemperature; + private BigDecimal maximumTemparature; + + public Location(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public BigDecimal getMinimumTemperature() { + return minimumTemperature; + } + + public void setMinimumTemperature(BigDecimal minimumTemperature) { + this.minimumTemperature = minimumTemperature; + } + + public BigDecimal getMaximumTemparature() { + return maximumTemparature; + } + + public void setMaximumTemparature(BigDecimal maximumTemparature) { + this.maximumTemparature = maximumTemparature; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java new file mode 100644 index 0000000000..abab4bdee8 --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package com.baeldung.testing.easymock; + +public class ServiceUnavailableException extends Exception { + + private static final long serialVersionUID = 6961151537340723535L; + +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java new file mode 100644 index 0000000000..1c6b11b17b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java @@ -0,0 +1,5 @@ +package com.baeldung.testing.easymock; + +public interface WeatherService { + void populateTemperature(Location location) throws ServiceUnavailableException; +} diff --git a/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java new file mode 100644 index 0000000000..fa8fa847ae --- /dev/null +++ b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.testing.easymock; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.math.BigDecimal; + +import org.easymock.EasyMock; +import org.easymock.EasyMockRule; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +public class ForecastProcessorUnitTest { + private static int MAX_TEMP = 90; + + @Rule + public EasyMockRule rule = new EasyMockRule(this); + + @TestSubject + private ForecastProcessor forecastProcessor = new ForecastProcessor(); + + @Mock + private WeatherService mockWeatherService; + + @Before + public void setUp() { + forecastProcessor.setWeatherService(mockWeatherService); + } + + @SuppressWarnings("unchecked") + @Test + public void givenLocationName_whenWeatherServicePopulatesTemperatures_thenMaxTempReturned() throws ServiceUnavailableException { + mockWeatherService.populateTemperature(EasyMock.anyObject(Location.class)); + EasyMock.expectLastCall() + .andAnswer(() -> { + Location passedLocation = (Location) EasyMock.getCurrentArguments()[0]; + passedLocation.setMaximumTemparature(new BigDecimal(MAX_TEMP)); + passedLocation.setMinimumTemperature(new BigDecimal(MAX_TEMP - 10)); + return null; + }); + EasyMock.replay(mockWeatherService); + BigDecimal maxTemperature = forecastProcessor.getMaximumTemperature("New York"); + EasyMock.verify(mockWeatherService); + assertThat(maxTemperature, equalTo(new BigDecimal(MAX_TEMP))); + } +} diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 158da176c6..e708d939e4 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -14,6 +14,31 @@ 1.0.0-SNAPSHOT ../../ + + + + + io.gatling + gatling-app + ${gatling.version} + + + io.gatling + gatling-recorder + ${gatling.version} + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + + + org.scala-lang + scala-library + ${scala.version} + + + @@ -77,52 +102,27 @@ simulation - - io.gatling - gatling-maven-plugin - ${gatling-maven-plugin.version} - - - test - - execute - - - true - - - - - - + + io.gatling + gatling-maven-plugin + ${gatling-maven-plugin.version} + + + test + + execute + + + true + + + + + + - - - - io.gatling - gatling-app - ${gatling.version} - - - io.gatling - gatling-recorder - ${gatling.version} - - - io.gatling.highcharts - gatling-charts-highcharts - ${gatling.version} - - - org.scala-lang - scala-library - ${scala.version} - - - - 1.8 1.8 diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md new file mode 100644 index 0000000000..7282a4efad --- /dev/null +++ b/testing-modules/junit-5-advanced/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher) diff --git a/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/xmlunit-2/src/main/resources/logback.xml b/testing-modules/junit-5-advanced/src/main/resources/logback.xml similarity index 100% rename from xmlunit-2/src/main/resources/logback.xml rename to testing-modules/junit-5-advanced/src/main/resources/logback.xml diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java index d6e023cfe8..429d6bac2a 100644 --- a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java @@ -9,7 +9,7 @@ class ReplaceUnderscoresGeneratorUnitTest { class when_doing_something { @Test - void then_should_happen_something() { + void then_something_should_happen() { } @Test diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java new file mode 100644 index 0000000000..a92c44a85b --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java @@ -0,0 +1,62 @@ +package com.baeldung.extensions.testwatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestWatcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestResultLoggerExtension implements TestWatcher, AfterAllCallback { + + private static final Logger LOG = LoggerFactory.getLogger(TestResultLoggerExtension.class); + + private List testResultsStatus = new ArrayList<>(); + + private enum TestResultStatus { + SUCCESSFUL, ABORTED, FAILED, DISABLED; + } + + @Override + public void testDisabled(ExtensionContext context, Optional reason) { + LOG.info("Test Disabled for test {}: with reason :- {}", context.getDisplayName(), reason.orElse("No reason")); + + testResultsStatus.add(TestResultStatus.DISABLED); + } + + @Override + public void testSuccessful(ExtensionContext context) { + LOG.info("Test Successful for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.SUCCESSFUL); + } + + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.ABORTED); + } + + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.FAILED); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + Map summary = testResultsStatus.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + LOG.info("Test result summary for {} {}", context.getDisplayName(), summary.toString()); + } + +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java new file mode 100644 index 0000000000..89666cf9b8 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.extensions.testwatcher; + +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.Assert; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +@ExtendWith(TestResultLoggerExtension.class) +class TestWatcherAPIUnitTest { + + @Test + void givenFalseIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(false); + } + + @Disabled + @Test + void givenTrueIsTrue_whenTestDisabledThenCaptureResult() { + Assert.assertTrue(true); + } + + @Test + void givenTrueIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(true); + } + + @Disabled("This test is disabled") + @Test + void givenFailure_whenTestDisabledWithReason_ThenCaptureResult() { + fail("Not yet implemented"); + } + +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..9b1777258c --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void divideNumbers() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void divideNumbers_failure() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void divideNumbers_error() { + SimpleCalculator.divideNumbers(10, 0); + } +} diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 6e44a9c071..dbe6803401 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,4 +1,10 @@ ### Relevant Articles: - +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) - [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) +- [JUnit 5 Temporary Directory Support](https://www.baeldung.com/junit-5-temporary-directory) +- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) +- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index f72c14ee65..68a0ceeee7 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -153,7 +153,6 @@ 5.4.2 1.2.0 5.4.2 - 1.4.196 5.0.6.RELEASE 2.21.0 diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java index 20fa372abd..eb8cab2462 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java @@ -17,7 +17,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -27,7 +27,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = resourceDirectory.toFile().getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -39,7 +39,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("/example_resource.txt")); + Assert.assertTrue(absolutePath.endsWith(File.separator + "example_resource.txt")); } } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 47db6587b4..d543b9b09b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,16 +1,9 @@ ### Relevant Articles: -- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) -- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) -- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) -- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) -- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) -- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) - [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) - [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md new file mode 100644 index 0000000000..b97ff8255c --- /dev/null +++ b/testing-modules/junit5-migration/README.md @@ -0,0 +1,2 @@ + +This is the code for the Junit 4 - Junit 5 Migration E-book. diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index 44014e96ab..2c53657481 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -145,7 +145,6 @@ 5.0 3.11 2.0.5.RELEASE - 1.4.197 \ No newline at end of file diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index acdd7eb2ac..7b6d6e7735 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -33,7 +33,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} @@ -94,11 +94,11 @@ 2.0.9.RELEASE 19.0 - 3.5 1.7.0 2.0.0.0 + 2.1.1 \ No newline at end of file diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java index 4f5ceb04e7..568492ca10 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java @@ -30,7 +30,7 @@ public class MockitoInjectIntoSpyUnitTest { private MyDictionary spyDic; @Test - public void whenUseInjectMocksAnnotation_thenCorrect2() { + public void whenUseInjectMocksAnnotation_thenCorrect() { Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); assertEquals("aMeaning", spyDic.getMeaning("aWord")); diff --git a/testing-modules/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml index ae36280300..e454f124ce 100644 --- a/testing-modules/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -49,7 +49,6 @@ 2.21.0 3.5.1 1.41 - diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 95a19c2557..8d40c668c0 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -14,6 +14,7 @@ + easy-random gatling groovy-spock junit-5 @@ -33,6 +34,8 @@ testing testng junit-5-basics + easymock junit-5-advanced + xmlunit-2 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 4ed10f0641..eb85c6c8be 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -194,14 +194,12 @@ 18.0 - 2.9.7 1.8 19.0 2.5 1.4.7 9.4.0.v20161208 - 3.5 3.2.2 4.4.5 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 6dad3be117..a1995ce9ff 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -151,7 +151,6 @@ 19.0 - 3.5 2.9.0 @@ -163,9 +162,6 @@ 4.5.2 4.1 - - - 2.6 \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 07888d7cdf..0970eabeff 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -4,4 +4,5 @@ - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) - [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) - [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation) -- [Override properties in Spring]() \ No newline at end of file +- [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) +- [Override properties in Spring]() diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 0eca9b6a7e..6f2700e2df 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -51,7 +51,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} org.springframework.data @@ -73,7 +73,7 @@ javax.servlet javax.servlet-api - ${servlet.api.version} + ${javax.servlet-api.version} @@ -94,7 +94,8 @@ 3.1.6 5.4.0 5.1.4.RELEASE - 4.0.1 + 4.0.1 + 2.1.1 \ No newline at end of file diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 7ee002ea8b..bd87cb5b22 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -23,6 +23,12 @@ ${junit.platform.version} test + + org.junit.platform + junit-platform-commons + ${junit.platform.version} + test + org.junit.vintage junit-vintage-engine @@ -59,6 +65,11 @@ selenium-remote-driver ${selenium-remote-driver.version} + + org.seleniumhq.selenium + selenium-chrome-driver + ${selenium-remote-driver.version} + @@ -76,7 +87,7 @@ org.junit.platform junit-platform-surefire-provider - ${junit.platform.version} + ${junit-platform-surefire-provider.version} @@ -99,16 +110,14 @@ - 5.1.0 - 1.0.1 - 4.12.1 - 2.8.2 - 2.21.0 - 5.0.1.RELEASE - 1.7.2 - 42.2.2 - 3.12.0 - 2.21.0 + 1.5.0 + 5.5.0 + 2.12.0 + 1.11.4 + 42.2.6 + 3.141.59 + 2.22.2 + 1.3.2 diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java index 0e52c4e9f7..0fdf0ede79 100644 --- a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java @@ -2,29 +2,26 @@ package com.baeldung.testconainers; import static org.junit.Assert.assertEquals; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.openqa.selenium.By; -import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; -import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.BrowserWebDriverContainer; -import org.testcontainers.containers.GenericContainer; public class WebDriverContainerLiveTest { @Rule public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer() - .withDesiredCapabilities(DesiredCapabilities.chrome()); + .withCapabilities(new ChromeOptions()); @Test public void whenNavigatedToPage_thenHeadingIsInThePage() { RemoteWebDriver driver = chrome.getWebDriver(); - driver.get("https://saucelabs.com/test/guinea-pig"); - String heading = driver.findElement(By.xpath("/html/body/h1")) + driver.get("http://example.com"); + String heading = driver.findElement(By.xpath("/html/body/div/h1")) .getText(); - assertEquals("This page is a Selenium sandbox", heading); + assertEquals("Example Domain", heading); } } diff --git a/xmlunit-2/README.md b/testing-modules/xmlunit-2/README.md similarity index 100% rename from xmlunit-2/README.md rename to testing-modules/xmlunit-2/README.md diff --git a/xmlunit-2/pom.xml b/testing-modules/xmlunit-2/pom.xml similarity index 94% rename from xmlunit-2/pom.xml rename to testing-modules/xmlunit-2/pom.xml index faefeca7a1..aa516bfcc5 100644 --- a/xmlunit-2/pom.xml +++ b/testing-modules/xmlunit-2/pom.xml @@ -1,15 +1,14 @@ 4.0.0 - com.baeldung xmlunit-2 - 1.0 xmlunit-2 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ @@ -23,7 +22,6 @@ xmlunit-core ${xmlunit.version} - diff --git a/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/testing-modules/xmlunit-2/src/main/resources/logback.xml b/testing-modules/xmlunit-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/xmlunit-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit-2/src/test/resources/control.xml b/testing-modules/xmlunit-2/src/test/resources/control.xml similarity index 100% rename from xmlunit-2/src/test/resources/control.xml rename to testing-modules/xmlunit-2/src/test/resources/control.xml diff --git a/xmlunit-2/src/test/resources/students.xml b/testing-modules/xmlunit-2/src/test/resources/students.xml similarity index 100% rename from xmlunit-2/src/test/resources/students.xml rename to testing-modules/xmlunit-2/src/test/resources/students.xml diff --git a/xmlunit-2/src/test/resources/students.xsd b/testing-modules/xmlunit-2/src/test/resources/students.xsd similarity index 100% rename from xmlunit-2/src/test/resources/students.xsd rename to testing-modules/xmlunit-2/src/test/resources/students.xsd diff --git a/xmlunit-2/src/test/resources/students_with_error.xml b/testing-modules/xmlunit-2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit-2/src/test/resources/students_with_error.xml rename to testing-modules/xmlunit-2/src/test/resources/students_with_error.xml diff --git a/xmlunit-2/src/test/resources/teachers.xml b/testing-modules/xmlunit-2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit-2/src/test/resources/teachers.xml rename to testing-modules/xmlunit-2/src/test/resources/teachers.xml diff --git a/xmlunit-2/src/test/resources/test.xml b/testing-modules/xmlunit-2/src/test/resources/test.xml similarity index 100% rename from xmlunit-2/src/test/resources/test.xml rename to testing-modules/xmlunit-2/src/test/resources/test.xml diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 089ebe67c1..e3d882bbda 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -187,7 +187,6 @@ 1.8 local mytheme - 3.0.0 3.0.0 diff --git a/vertx-and-rxjava/.gitignore b/vertx-and-rxjava/.gitignore new file mode 100644 index 0000000000..3aba11e2fd --- /dev/null +++ b/vertx-and-rxjava/.gitignore @@ -0,0 +1 @@ +/.vertx \ No newline at end of file diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 2492951d1a..200ca7577f 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -141,10 +141,6 @@ 2.8.0 4.1 - - 3.5 - 2.5 - 3.0.1 3.0.0 diff --git a/xml/pom.xml b/xml/pom.xml index ba6a734dc9..540b1fc03b 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 xml @@ -14,7 +15,7 @@ - dom4j + org.dom4j dom4j ${dom4j.version} @@ -23,29 +24,52 @@ jaxen ${jaxen.version} - + + org.jooq + joox-java-6 + ${joox.version} + org.jdom jdom2 ${jdom2.version} - - javax.xml + javax.xml.bind jaxb-api - 2.1 + ${jaxb-api.version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb-impl.version} + + + com.sun.xml.bind + jaxb-core + ${jaxb-core.version} javax.xml jaxp-api - 1.4.2 + ${jaxp-api.version} javax.xml.stream stax-api - 1.0-2 + ${stax-api.version} + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} - commons-io @@ -76,6 +100,31 @@ commons-lang ${commons-lang.version} + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + org.xmlunit + xmlunit-assertj + ${xmlunit-assertj.version} + test + @@ -86,6 +135,16 @@ true + + + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + @@ -213,7 +272,8 @@ - + maven-assembly-plugin ${project.basedir} @@ -232,8 +292,10 @@ - make-assembly - package + make-assembly + package attached @@ -246,13 +308,22 @@ - 1.6.1 - 1.1.6 + 2.1.1 + 1.2.0 2.0.6 + 1.6.2 2.5 4.1 1.2.4.5 - + 2.3.1 + 1.4.2 + 2.3.0.1 + 2.3.2 + 1.0-2 + 3.12.2 + 2.6.3 + 5.5.0 + 1.21 3.5 2.4 @@ -260,6 +331,8 @@ 1.3.1 + 3.8.0 + 2.22.2 diff --git a/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java new file mode 100644 index 0000000000..a1922ad224 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java @@ -0,0 +1,45 @@ +package com.baeldung.xml.attribute; + +import org.dom4j.*; +import org.dom4j.io.DocumentSource; +import org.dom4j.io.SAXReader; + +import javax.xml.XMLConstants; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import java.io.StringWriter; +import java.io.Writer; +import java.util.List; + +public class Dom4jTransformer { + private final Document input; + + public Dom4jTransformer(String resourcePath) throws DocumentException { + // 1- Build the doc from the XML file + SAXReader xmlReader = new SAXReader(); + this.input = xmlReader.read(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerException { + // 2- Locate the node(s) with xpath, we can use index and iterator too. + String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue); + XPath xpath = DocumentHelper.createXPath(expr); + List nodes = xpath.selectNodes(input); + // 3- Make the change on the selected nodes + for (int i = 0; i < nodes.size(); i++) { + Element element = (Element) nodes.get(i); + element.addAttribute(attribute, newValue); + } + // 4- Save the result to a new XML doc + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer xformer = factory.newTransformer(); + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + Writer output = new StringWriter(); + xformer.transform(new DocumentSource(input), new StreamResult(output)); + return output.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java new file mode 100644 index 0000000000..a2266a2b44 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java @@ -0,0 +1,63 @@ +package com.baeldung.xml.attribute; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class JaxpTransformer { + + private Document input; + + public JaxpTransformer(String resourcePath) throws SAXException, IOException, ParserConfigurationException { + // 1- Build the doc from the XML file + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + input = factory.newDocumentBuilder() + .parse(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { + // 2- Locate the node(s) with xpath + XPath xpath = XPathFactory.newInstance() + .newXPath(); + NodeList nodes = (NodeList) xpath.evaluate(String.format("//*[contains(@%s, '%s')]", attribute, oldValue), input, XPathConstants.NODESET); + // 3- Make the change on the selected nodes + for (int i = 0; i < nodes.getLength(); i++) { + Element value = (Element) nodes.item(i); + value.setAttribute(attribute, newValue); + } + //Stream api syntax + // IntStream + // .range(0, nodes.getLength()) + // .mapToObj(i -> (Element) nodes.item(i)) + // .forEach(value -> value.setAttribute(attribute, newValue)); + // 4- Save the result to a new XML doc + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer xformer = factory.newTransformer(); + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + Writer output = new StringWriter(); + xformer.transform(new DOMSource(input), new StreamResult(output)); + return output.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java new file mode 100644 index 0000000000..d36d60ec59 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java @@ -0,0 +1,38 @@ +package com.baeldung.xml.attribute; + +import org.joox.JOOX; +import org.joox.Match; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; + +import static org.joox.JOOX.$; + +public class JooxTransformer { + + private final Document input; + + public JooxTransformer(String resourcePath) throws SAXException, IOException { + // 1- Build the doc from the XML file + DocumentBuilder builder = JOOX.builder(); + input = builder.parse(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerFactoryConfigurationError { + // 2- Select the document + Match $ = $(input); + // 3 - Find node to modify + String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue); + $ + // .find("to") or with xpath + .xpath(expr) + .get() + .stream() + .forEach(e -> e.setAttribute(attribute, newValue)); + // 4- Return result as String + return $.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java b/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java new file mode 100644 index 0000000000..064e181713 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java @@ -0,0 +1,72 @@ +package com.baeldung.xml.attribute.jmh; + +import org.dom4j.DocumentException; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; +import org.xml.sax.SAXException; + +import com.baeldung.xml.attribute.Dom4jTransformer; +import com.baeldung.xml.attribute.JaxpTransformer; +import com.baeldung.xml.attribute.JooxTransformer; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPathExpressionException; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Benchmark) +public class AttributeBenchMark { + + public static void main(String[] args) throws RunnerException { + Options opt = new OptionsBuilder() + .include(AttributeBenchMark.class.getSimpleName()) + .forks(1) + .build(); + new Runner(opt).run(); + } + + @Benchmark + public String dom4jBenchmark() throws DocumentException, TransformerException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } + + @Benchmark + public String jooxBenchmark() throws IOException, SAXException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } + + @Benchmark + public String jaxpBenchmark() throws TransformerException, ParserConfigurationException, SAXException, IOException, XPathExpressionException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JaxpTransformer transformer = new JaxpTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } +} diff --git a/xml/src/main/resources/xml/attribute.xml b/xml/src/main/resources/xml/attribute.xml new file mode 100644 index 0000000000..c8fa3f1071 --- /dev/null +++ b/xml/src/main/resources/xml/attribute.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/main/resources/xml/attribute_expected.xml b/xml/src/main/resources/xml/attribute_expected.xml new file mode 100644 index 0000000000..1d5d7b0cea --- /dev/null +++ b/xml/src/main/resources/xml/attribute_expected.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java new file mode 100644 index 0000000000..485744f9a5 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.xml.attribute; + +import org.dom4j.DocumentException; +import org.junit.jupiter.api.Test; + +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +/** + * Unit test for {@link Dom4jTransformer}. + */ +public class Dom4jProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws TransformerFactoryConfigurationError, TransformerException, DocumentException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + + @Test + public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + String expectedXml = new String(Files.readAllBytes((Paths.get(getClass() + .getResource("/xml/attribute_expected.xml") + .toURI())))); + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result) + .and(expectedXml) + .areSimilar(); + } + +} diff --git a/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java new file mode 100644 index 0000000000..8394016dbd --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.xml.attribute; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.xpath.XPathExpressionException; + +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; + +/** + * Unit test for {@link JaxpTransformer}. + */ +public class JaxpProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { + String path = getClass().getResource("/xml/attribute.xml") + .toString(); + JaxpTransformer transformer = new JaxpTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + +} diff --git a/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java new file mode 100644 index 0000000000..38c7c59789 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.xml.attribute; + +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; + +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +/** + * Unit test for {@link JooxTransformer}. + */ +public class JooxProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, TransformerFactoryConfigurationError { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + + @Test + public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, URISyntaxException, SAXException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + String expectedXml = new String(Files.readAllBytes((Paths.get(getClass() + .getResource("/xml/attribute_expected.xml") + .toURI())))); + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result) + .and(expectedXml) + .areSimilar(); + } + +} diff --git a/xml/src/test/resources/xml/attribute.xml b/xml/src/test/resources/xml/attribute.xml new file mode 100644 index 0000000000..c8fa3f1071 --- /dev/null +++ b/xml/src/test/resources/xml/attribute.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/test/resources/xml/attribute_expected.xml b/xml/src/test/resources/xml/attribute_expected.xml new file mode 100644 index 0000000000..1d5d7b0cea --- /dev/null +++ b/xml/src/test/resources/xml/attribute_expected.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xstream/pom.xml b/xstream/pom.xml index f75e10fc7d..b98e258599 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../pom.xml @@ -28,8 +29,8 @@ - 1.4.9 + 1.4.10 1.3.8 - \ No newline at end of file + diff --git a/xstream/src/main/java/com/baeldung/rce/App.java b/xstream/src/main/java/com/baeldung/rce/App.java new file mode 100644 index 0000000000..3720c7fa93 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/App.java @@ -0,0 +1,92 @@ +package com.baeldung.rce; + +import com.sun.net.httpserver.HttpServer; +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.NoTypePermission; +import com.thoughtworks.xstream.security.NullPermission; +import com.thoughtworks.xstream.security.PrimitiveTypePermission; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; + +/** + * Web application which is intentionally vulnerable to an XStream remote code + * exploitation (RCE). + * + *

+ * This test application is meant to maintain a set of {@link Person} models. It + * exposes a "/persons" endpoint which supports the following operations: + * + *

    + *
  1. {@code POST} XML for adding a new {@link Person} to the set + *
  2. {@code GET} for retrieving the set of {@link Person} models as XML + *
+ * + * The {@code POST} handler is vulnerable to an RCE exploit. + */ +public final class App { + + public static App createHardened(int port) { + final XStream xstream = new XStream(); + xstream.addPermission(NoTypePermission.NONE); + xstream.addPermission(NullPermission.NULL); + xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); + xstream.allowTypes(new Class[] { Person.class }); + return new App(port, xstream); + } + + public static App createVulnerable(int port) { + return new App(port, new XStream()); + } + + private final int port; + private final Set persons; + private final XStream xstream; + private HttpServer server; + + private App(int port, XStream xstream) { + this.port = port; + persons = new HashSet<>(); + // this app is vulnerable because XStream security is not configured + this.xstream = xstream; + this.xstream.alias("person", Person.class); + } + + void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("localhost", port), 0); + server.createContext("/persons", exchange -> { + switch (exchange.getRequestMethod()) { + case "POST": + final Person person = (Person) xstream.fromXML(exchange.getRequestBody()); + persons.add(person); + exchange.sendResponseHeaders(201, 0); + exchange.close(); + break; + case "GET": + exchange.sendResponseHeaders(200, 0); + xstream.toXML(persons, exchange.getResponseBody()); + exchange.close(); + break; + default: + exchange.sendResponseHeaders(405, 0); + exchange.close(); + } + }); + server.start(); + } + + void stop() { + if (server != null) { + server.stop(0); + } + } + + int port() { + if (server == null) + throw new IllegalStateException("Server not started"); + return server.getAddress() + .getPort(); + } +} diff --git a/xstream/src/main/java/com/baeldung/rce/Person.java b/xstream/src/main/java/com/baeldung/rce/Person.java new file mode 100644 index 0000000000..336c47798b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.rce; + +import java.util.Objects; + +/** Person model */ +public final class Person { + + private String first; + private String last; + + public String getFirst() { + return first; + } + + public void setFirst(String first) { + this.first = first; + } + + public String getLast() { + return last; + } + + public void setLast(String last) { + this.last = last; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Person)) { + return false; + } + Person person = (Person) o; + return Objects.equals(first, person.first) && Objects.equals(last, person.last); + } + + @Override + public int hashCode() { + return Objects.hash(first, last); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java new file mode 100644 index 0000000000..3b541ae099 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rce; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.SocketException; +import java.net.URL; + +import static org.junit.Assert.assertTrue; + +/** + * Unit test which demonstrates a remote code exploit against the {@link App} + * server. Sends an XML request containing an attack payload to the {@code POST} + * endpoint. + */ +public final class AppUnitTest { + + private App app; + + /** start a new web server */ + @Before + public void before() throws IOException { + app = App.createVulnerable(0); + app.start(); + } + + /** stop the web server */ + @After + public void after() { + if (app != null) + app.stop(); + } + + /** + * Test passes when an {@link IOException} is thrown because this indicates that + * the attacker caused the application to fail in some way. This does not + * actually confirm that the exploit took place, because the RCE is a + * side-effect that is difficult to observe. + */ + @Test(expected = SocketException.class) + public void givenAppIsVulneable_whenExecuteRemoteCodeWhichThrowsException_thenThrowsException() throws IOException { + // POST the attack.xml to the application's /persons endpoint + final URL url = new URL("http://localhost:" + app.port() + "/persons"); + final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setUseCaches(false); + connection.setRequestProperty("Content-Type", "application/xml"); + connection.connect(); + try (OutputStream os = connection.getOutputStream(); InputStream is = AppUnitTest.class.getResourceAsStream("/attack.xml")) { + byte[] buffer = new byte[1024]; + while (is.read(buffer) > 0) { + os.write(buffer); + } + } + final int rc = connection.getResponseCode(); + connection.disconnect(); + assertTrue(rc >= 400); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java new file mode 100644 index 0000000000..16c906abfc --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java @@ -0,0 +1,7 @@ +package com.baeldung.rce; + +/** + * Indicates a successful remote code execution attack has taken place. + */ +final class AttackExploitedException extends RuntimeException { +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java new file mode 100644 index 0000000000..16ed143f7a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java @@ -0,0 +1,13 @@ +package com.baeldung.rce; + +/** + * Class which contains an action to throw {@link AttackExploitedException}. + * This helper is used by {@link AppTest} to determine when the remote code + * exploit has taken place. + */ +final class AttackExploitedExceptionThrower { + + public void throwAttackExploitedException() { + throw new AttackExploitedException(); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java new file mode 100644 index 0000000000..d762813b22 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.rce; + +import com.thoughtworks.xstream.XStream; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/** + * Demonstrates XStream basics + */ +public final class XStreamBasicsUnitTest { + + private XStream xstream; + + @Before + public void before() { + xstream = new XStream(); + xstream.alias("person", Person.class); + } + + @Test + public void whenWritePerson_thenWritesExpectedXml() { + Person person = new Person(); + person.setFirst("John"); + person.setLast("Smith"); + + String xml = xstream.toXML(person); + + // @formatter:off + String expected = "" + + "\n" + + " John\n" + + " Smith\n" + + ""; + // @formatter:on + assertEquals(expected, xml); + + } + + @Test + public void whenReadXmlAsPerson_thenReturnsNewPerson() { + // @formatter:off + String xml = "" + + "" + + " John" + + " Smith" + + ""; + // @formatter:on + + Person person = (Person) xstream.fromXML(xml); + + Person expected = new Person(); + expected.setFirst("John"); + expected.setLast("Smith"); + assertEquals(person, expected); + } + + @Test + public void givenXmlRepresentationOfMap_whenDeserialize_thenBuildsMap() { + // @formatter:off + String xml = "" + + "" + + " " + + " foo" + + " 10" + + " " + + ""; + // @formatter:on + @SuppressWarnings("unchecked") + Map actual = (Map) xstream.fromXML(xml); + + final Map expected = Collections.singletonMap("foo", 10); + + assertEquals(expected, actual); + } + +} diff --git a/xstream/src/test/resources/attack.xml b/xstream/src/test/resources/attack.xml new file mode 100644 index 0000000000..8a5713648c --- /dev/null +++ b/xstream/src/test/resources/attack.xml @@ -0,0 +1,12 @@ + + foo + + java.lang.Comparable + + + + throwAttackExploitedException + + + diff --git a/xstream/src/test/resources/calculator-attack.xml b/xstream/src/test/resources/calculator-attack.xml new file mode 100644 index 0000000000..ae24843dc6 --- /dev/null +++ b/xstream/src/test/resources/calculator-attack.xml @@ -0,0 +1,16 @@ + + foo + + java.lang.Comparable + + + + open + /Applications/Calculator.app + + + start + + +