diff --git a/.gitignore b/.gitignore index 5be11c71ff..2edea19340 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ */bin/* +bin/ *.class @@ -21,6 +22,9 @@ *.iws out/ +# VSCode +.vscode/ + # Mac .DS_Store diff --git a/README.md b/README.md index 1030cbb09c..4cad075cc3 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ -The "REST with Spring" Classes +The Courses ============================== -Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material):
-**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** -And here's the Master Class of Learn Spring Security:
-**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** +Here's the new "Learn Spring" course:
+**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)** + +Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material):
+**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** + +And here's the Master Class of "Learn Spring Security":
+**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** @@ -15,7 +19,7 @@ Java and Spring Tutorials This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem. A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. -In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. +In additional to Spring, the modules here are covering a number of aspects in Java. Building the project @@ -32,8 +36,15 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -#Running Tests +Working with the IDE +==================== +This repo contains a large number of modules. +When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ. + + +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-3/README.md b/algorithms-miscellaneous-3/README.md index 71541cd2b3..6a38df484a 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -1,4 +1,4 @@ -## Relevant articles: +## Relevant Articles: - [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique) - [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) @@ -6,4 +6,4 @@ - [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](https://www.baeldung.com/folding-hashing-technique) +- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java new file mode 100644 index 0000000000..376b196aa1 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java @@ -0,0 +1,30 @@ +package com.baeldung.algorithms.stringsortingbynumber; + +import java.util.Comparator; + +public final class NaturalOrderComparators { + + private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]"; + + private NaturalOrderComparators() { + throw new AssertionError("Let's keep this static"); + } + + public static Comparator createNaturalOrderRegexComparator() { + return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber); + } + + private static double parseStringToNumber(String input){ + + final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, ""); + + if("".equals(digitsOnly)) return 0; + + try{ + return Double.parseDouble(digitsOnly); + }catch (NumberFormatException nfe){ + return 0; + } + } + +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java new file mode 100644 index 0000000000..549151bc93 --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.algorithms.stringsortingbynumber; + +import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class NaturalOrderComparatorsUnitTest { + + @Test + public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { + + List testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5 + + List expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" ); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + assertEquals(expected, testStrings); + + } + + @Test + public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { + + List testStrings = Arrays.asList("a", "c", "d", "e"); + List expected = new ArrayList<>(testStrings); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + assertEquals(expected, testStrings); + } +} \ No newline at end of file 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-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index e3647b9c57..24e7b4e0b2 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -82,7 +82,6 @@ - 1.8 2.0.11 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/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index 53b3e6a7ec..ba3fd0802b 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -175,8 +175,6 @@ 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/main/groovy/com/baeldung/metaprogramming/Employee.groovy b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy new file mode 100644 index 0000000000..f49d0f906b --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy @@ -0,0 +1,45 @@ +package com.baeldung.metaprogramming + +import groovy.transform.AutoClone +import groovy.transform.Canonical +import groovy.transform.EqualsAndHashCode +import groovy.transform.ToString +import groovy.transform.TupleConstructor +import groovy.util.logging.* + +@Canonical +@TupleConstructor +@EqualsAndHashCode +@ToString(includePackage=false, excludes=['id']) +@Log +@AutoClone +class Employee { + + long id + String firstName + String lastName + int age + + //method to catch missing property's getter + def propertyMissing(String propertyName) { + log.info "$propertyName is not available" + "property '$propertyName' is not available" + } + + //method to catch missing property's setter + def propertyMissing(String propertyName, propertyValue) { + println "property '$propertyName' is not available" + log.info "$propertyName is not available" + "property '$propertyName' is not available" + } + + def methodMissing(String methodName, def methodArgs) { + log.info "$methodName is not defined" + "method '$methodName' is not defined" + } + + def logEmp() { + log.info "Employee: $lastName, $firstName is of $age years age" + } + +} \ No newline at end of file diff --git a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy new file mode 100644 index 0000000000..65591cae8d --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy @@ -0,0 +1,30 @@ +package com.baeldung.metaprogramming.extension + +import com.baeldung.metaprogramming.Employee + +class BasicExtensions { + + static int getYearOfBirth(Employee self) { + return (new Date().getYear() + 1900) - self.age; + } + + static String capitalize(String self) { + return self.substring(0, 1).toUpperCase() + self.substring(1) + } + + static void printCounter(Integer self) { + while (self>0) { + println self + self-- + } + } + + static Long square(Long self) { + return self*self + } + + static BigDecimal cube(BigDecimal self) { + return self*self*self + } + +} \ No newline at end of file diff --git a/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/StaticEmployeeExtension.groovy b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/StaticEmployeeExtension.groovy new file mode 100644 index 0000000000..ab2aac38ea --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/StaticEmployeeExtension.groovy @@ -0,0 +1,10 @@ +package com.baeldung.metaprogramming.extension + +import com.baeldung.metaprogramming.Employee + +class StaticEmployeeExtension { + + static Employee getDefaultObj(Employee self) { + return new Employee(firstName: "firstName", lastName: "lastName", age: 20) + } +} \ No newline at end of file diff --git a/core-groovy-2/src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule b/core-groovy-2/src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule new file mode 100644 index 0000000000..967108b846 --- /dev/null +++ b/core-groovy-2/src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule @@ -0,0 +1,4 @@ +moduleName=core-groovy-2 +moduleVersion=1.0-SNAPSHOT +extensionClasses=com.baeldung.metaprogramming.extension.BasicExtensions +staticExtensionClasses=com.baeldung.metaprogramming.extension.StaticEmployeeExtension 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-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy new file mode 100644 index 0000000000..8066b10f9b --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -0,0 +1,118 @@ +package com.baeldung.metaprogramming + +import groovy.time.TimeCategory + +class MetaprogrammingUnitTest extends GroovyTestCase { + + Employee emp = new Employee(firstName: "Norman", lastName: "Lewis") + + void testPropertyMissing() { + assert emp.address == "property 'address' is not available" + } + + void testMethodMissing() { + Employee emp = new Employee() + try { + emp.getFullName() + } catch(MissingMethodException e) { + println "method is not defined" + } + assert emp.getFullName() == "method 'getFullName' is not defined" + } + + void testMetaClassProperty() { + Employee.metaClass.address = "" + emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US") + assert emp.address == "US" + } + + void testMetaClassMethod() { + emp.metaClass.getFullName = { + "$lastName, $firstName" + } + assert emp.getFullName() == "Lewis, Norman" + } + + void testMetaClassConstructor() { + try { + Employee emp = new Employee("Norman") + } catch(GroovyRuntimeException e) { + assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)" + } + + Employee.metaClass.constructor = { String firstName -> + new Employee(firstName: firstName) + } + + Employee norman = new Employee("Norman") + assert norman.firstName == "Norman" + assert norman.lastName == null + } + + void testJavaMetaClass() { + String.metaClass.capitalize = { String str -> + str.substring(0, 1).toUpperCase() + str.substring(1); + } + assert "norman".capitalize() == "Norman" + } + + void testEmployeeExtension() { + Employee emp = new Employee(age: 28) + assert emp.getYearOfBirth() == 1991 + } + + void testJavaClassesExtensions() { + 5.printCounter() + + assert 40l.square() == 1600l + + assert (2.98).cube() == 26.463592 + } + + void testStaticEmployeeExtension() { + assert Employee.getDefaultObj().firstName == "firstName" + assert Employee.getDefaultObj().lastName == "lastName" + assert Employee.getDefaultObj().age == 20 + } + + void testToStringAnnotation() { + Employee employee = new Employee() + employee.id = 1 + employee.firstName = "norman" + employee.lastName = "lewis" + employee.age = 28 + + assert employee.toString() == "Employee(norman, lewis, 28)" + } + + void testTupleConstructorAnnotation() { + Employee norman = new Employee(1, "norman", "lewis", 28) + assert norman.toString() == "Employee(norman, lewis, 28)" + + Employee snape = new Employee(2, "snape") + assert snape.toString() == "Employee(snape, null, 0)" + + } + + void testEqualsAndHashCodeAnnotation() { + Employee norman = new Employee(1, "norman", "lewis", 28) + Employee normanCopy = new Employee(1, "norman", "lewis", 28) + assert norman.equals(normanCopy) + assert norman.hashCode() == normanCopy.hashCode() + } + + void testAutoCloneAnnotation() { + try { + Employee norman = new Employee(1, "norman", "lewis", 28) + def normanCopy = norman.clone() + assert norman == normanCopy + } catch(CloneNotSupportedException e) { + e.printStackTrace() + } + } + + void testLoggingAnnotation() { + Employee employee = new Employee(1, "Norman", "Lewis", 28) + employee.logEmp() + } +} \ No newline at end of file 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..6c603e4dea --- /dev/null +++ b/core-java-modules/core-java-12/README.md @@ -0,0 +1,4 @@ +## 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 245fa93ba7..d11510b2aa 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -7,3 +7,4 @@ - [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) +- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface) 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-2/.gitignore b/core-java-modules/core-java-arrays-2/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/.gitignore @@ -0,0 +1,25 @@ +*.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 +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-arrays/README.MD b/core-java-modules/core-java-arrays-2/README.MD similarity index 100% rename from core-java-arrays/README.MD rename to core-java-modules/core-java-arrays-2/README.MD diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml new file mode 100644 index 0000000000..bfe8a349e1 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.baeldung + core-java-arrays-2 + 0.1.0-SNAPSHOT + core-java-arrays-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + core-java-arrays-2 + + + src/main/resources + true + + + + + + + + 3.9 + + 3.10.0 + + + diff --git a/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java similarity index 100% rename from core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java new file mode 100644 index 0000000000..71e2840f45 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/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/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java similarity index 100% rename from core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java new file mode 100644 index 0000000000..5f670f4a59 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.array.looping; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class LoopDiagonallyUnitTest { + + @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/core-java-arrays/README.md b/core-java-modules/core-java-arrays/README.md index b5f71cc253..45feff3edc 100644 --- a/core-java-modules/core-java-arrays/README.md +++ b/core-java-modules/core-java-arrays/README.md @@ -7,7 +7,7 @@ - [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value) - [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) - [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays) -- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) +- [Multi-Dimensional Arrays In Java](http://www.baeldung.com/java-jagged-arrays) - [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average) - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) @@ -16,3 +16,4 @@ - [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) - [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) - [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) +- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-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 index ec612fd53b..78a9a8f4d1 100644 --- 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 @@ -2,7 +2,10 @@ package com.baeldung.array; import com.baeldung.arraycopy.model.Employee; +import java.util.Comparator; + public class SortedArrayChecker { + boolean isSorted(int[] array, int length) { if (array == null || length < 2) return true; @@ -22,7 +25,7 @@ public class SortedArrayChecker { return true; } - boolean isSorted(String[] array, int length) { + boolean isSorted(Comparable[] array, int length) { if (array == null || length < 2) return true; @@ -32,40 +35,31 @@ public class SortedArrayChecker { 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) { + boolean isSorted(Comparable[] array) { for (int i = 0; i < array.length - 1; ++i) { - if (array[i].getName().compareTo(array[i + 1].getName()) > 0) + if (array[i].compareTo(array[i + 1]) > 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; + boolean isSorted(Object[] array, Comparator comparator) { + for (int i = 0; i < array.length - 1; ++i) { + if (comparator.compare(array[i], (array[i + 1])) > 0) + return false; + } + + return true; } - return true; -} - - boolean isSortedByAge(Employee[] array, int length) { + boolean isSorted(Object[] array, Comparator comparator, int length) { if (array == null || length < 2) return true; - if (array[length - 2].getAge() > array[length - 1].getAge()) + if (comparator.compare(array[length - 2], array[length - 1]) > 0) return false; - return isSortedByAge(array, length - 1); + return isSorted(array, comparator, length - 1); } } 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 index 29866a3c22..7971e0eab7 100644 --- 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 @@ -4,32 +4,33 @@ import com.baeldung.arraycopy.model.Employee; import org.junit.Before; import org.junit.Test; +import java.util.Comparator; + import static org.assertj.core.api.Assertions.assertThat; -class SortedArrayCheckerUnitTest { - +public 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 = { + private static 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 = { + private static 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 = { + private static 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 = { + private static final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { new Employee(1, "Marta", 27), new Employee(2, "Carlos", 26), new Employee(3, "Daniel", 31)}; @@ -61,13 +62,18 @@ class SortedArrayCheckerUnitTest { @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.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).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); + assertThat(sortedArrayChecker + .isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length)) + .isEqualTo(true); + assertThat(sortedArrayChecker + .isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), 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-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..79e5bad23a --- /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-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-io/src/main/java/com/baeldung/files/Main.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java new file mode 100644 index 0000000000..c3bcd048a4 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java @@ -0,0 +1,24 @@ +package com.baeldung.files; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; + +public class Main { + + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + + public static void main(String... args) throws Exception { + System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME)); + } +} diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java new file mode 100644 index 0000000000..076825d76c --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java @@ -0,0 +1,112 @@ +package com.baeldung.files; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileChannel.MapMode; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Stream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; + +public class NumberOfLineFinder { + + public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) { + int lines = 0; + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + while (reader.readLine() != null) { + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) { + int lines = 0; + try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) { + reader.skip(Integer.MAX_VALUE); + lines = reader.getLineNumber() + 1; + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingScanner(String fileName) { + int lines = 0; + try (Scanner scanner = new Scanner(new FileReader(fileName))) { + while (scanner.hasNextLine()) { + scanner.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) { + int lines = 0; + try (Stream fileStream = Files.lines(Paths.get(fileName))) { + lines = (int) fileStream.count(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) { + int lines = 1; + try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) { + ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size()); + while (byteBuffer.hasRemaining()) { + byte currentChar = byteBuffer.get(); + if (currentChar == '\n') { + lines++; + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) { + int lines = 0; + try { + LineIterator lineIterator = FileUtils.lineIterator(new File(fileName)); + while (lineIterator.hasNext()) { + lineIterator.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) { + int lines = 0; + try { + List lineItems = com.google.common.io.Files.readLines(Paths.get(fileName) + .toFile(), Charset.defaultCharset()); + lines = lineItems.size(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java new file mode 100644 index 0000000000..6f0427ebd2 --- /dev/null +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.file; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NumberOfLineFinderUnitTest { + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + private static final int ACTUAL_LINE_COUNT = 45; + + @Test + public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingScanner_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + +} diff --git a/core-java-modules/core-java-jpms/README.md b/core-java-modules/core-java-jpms/README.md new file mode 100644 index 0000000000..5c424711bc --- /dev/null +++ b/core-java-modules/core-java-jpms/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Design Strategies for Decoupling Java Modules](https://www.baeldung.com/java-modules-decoupling-design-strategies) 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/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java new file mode 100644 index 0000000000..6be9a18781 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class Car { + + private List wheels; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java new file mode 100644 index 0000000000..96c07f13a4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java @@ -0,0 +1,13 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class CarWithStaticInnerWheel { + + private List wheels; + + public static class Wheel { + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java new file mode 100644 index 0000000000..1f38ea85ad --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.aggregation; + +public class Wheel { + + private Car car; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java new file mode 100644 index 0000000000..4c748e8084 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.association; + +public class Child { + + private Mother mother; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java new file mode 100644 index 0000000000..0e8edef125 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.association; + +import java.util.List; + +public class Mother { + + private List children; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java new file mode 100644 index 0000000000..1ab44f73fa --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java @@ -0,0 +1,18 @@ +package com.baeldung.relationships.composition; + +import java.util.List; + +public class Building { + + private String address; + private List rooms; + + public class Room { + + public String getBuildingAddress() { + return Building.this.address; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java new file mode 100644 index 0000000000..4e3411cf30 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java @@ -0,0 +1,28 @@ +package com.baeldung.relationships.composition; + +public class BuildingWithDefinitionRoomInMethod { + + public Room createAnonymousRoom() { + return new Room() { + @Override + public void doInRoom() {} + }; + } + + public Room createInlineRoom() { + class InlineRoom implements Room { + @Override + public void doInRoom() {} + } + return new InlineRoom(); + } + + public Room createLambdaRoom() { + return () -> {}; + } + + public interface Room { + void doInRoom(); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java new file mode 100644 index 0000000000..63cfd1b89e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Department { + + private List professors; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java new file mode 100644 index 0000000000..8e1258c3e6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java @@ -0,0 +1,10 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Professor { + + private List department; + private List friends; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java new file mode 100644 index 0000000000..e5e518e0f1 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class University { + + private List department; + +} 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-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml new file mode 100644 index 0000000000..58cab9d507 --- /dev/null +++ b/core-java-modules/core-java-lang-operators/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + com.baeldung + core-java-lang-operators + 0.1.0-SNAPSHOT + core-java-lang-operators + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + core-java-lang-operators + + + src/main/resources + true + + + + + + + 3.10.0 + + + diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Circle.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Circle.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Circle.java rename to core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Circle.java diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Ring.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Ring.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Ring.java rename to core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Ring.java diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Round.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Round.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Round.java rename to core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Round.java diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Shape.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Shape.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Shape.java rename to core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Shape.java diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Triangle.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Triangle.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/keyword/Triangle.java rename to core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/keyword/Triangle.java diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/incrementdecrementunaryoperators/IncrementDecrementUnaryOperatorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/incrementdecrementunaryoperators/IncrementDecrementUnaryOperatorUnitTest.java new file mode 100644 index 0000000000..8fbc2eeab8 --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/incrementdecrementunaryoperators/IncrementDecrementUnaryOperatorUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.incrementdecrementunaryoperators; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class IncrementDecrementUnaryOperatorUnitTest { + + @Test + public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + ++operand; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() { + int operand = 1; + int number = ++operand; + assertThat(number).isEqualTo(2); + } + + @Test + public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + --operand; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() { + int operand = 1; + int number = --operand; + assertThat(number).isEqualTo(0); + } + + @Test + public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + operand++; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand++; + assertThat(number).isEqualTo(1); + } + + @Test + public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + operand--; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand--; + assertThat(number).isEqualTo(1); + } +} diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Car.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Car.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Car.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Car.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Diesel.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Diesel.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Diesel.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Diesel.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Engine.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Engine.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Engine.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Engine.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Vehicle.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Vehicle.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Vehicle.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/diamond/Vehicle.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/test/InstanceOfUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/modulo/ModuloUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/modulo/ModuloUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/modulo/ModuloUnitTest.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/modulo/ModuloUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java rename to core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/README.md b/core-java-modules/core-java-lang-syntax/README.md index 81c3d6c354..3293e9b23d 100644 --- a/core-java-modules/core-java-lang-syntax/README.md +++ b/core-java-modules/core-java-lang-syntax/README.md @@ -18,3 +18,4 @@ - [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) - [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) - [Java instanceof Operator](https://www.baeldung.com/java-instanceof) +- [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop) 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-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml new file mode 100644 index 0000000000..8a26f6ab9f --- /dev/null +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + core-java-networking-2 + core-java-networking-2 + jar + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + + + + core-java-networking-2 + + diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java new file mode 100644 index 0000000000..b99e74f8bf --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java @@ -0,0 +1,25 @@ +package com.baeldung.url; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class UrlChecker { + + public int getResponseCodeForURL(String address) throws IOException { + return getResponseCodeForURLUsing(address, "GET"); + } + + public int getResponseCodeForURLUsingHead(String address) throws IOException { + return getResponseCodeForURLUsing(address, "HEAD"); + } + + private int getResponseCodeForURLUsing(String address, String method) throws IOException { + HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false + final URL url = new URL(address); + HttpURLConnection huc = (HttpURLConnection) url.openConnection(); + huc.setRequestMethod(method); + return huc.getResponseCode(); + } + +} diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java new file mode 100644 index 0000000000..5e295e65a0 --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.url; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class UrlCheckerUnitTest { + + @Test + public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com"); + assertEquals(200, responseCode); + } + + @Test + public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl"); + assertEquals(404, responseCode); + } + + @Test + public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURL("http://www.example.com"); + assertEquals(200, responseCode); + } + + @Test + public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl"); + assertEquals(404, responseCode); + } + +} 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 9034c3b3b1..1ac3b6c089 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: +## Relevant Articles: -- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date) +- [Determine File Creation Date in Java](https://www.baeldung.com/java-file-creation-date) diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index f60e3ba03d..eb981c0907 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -19,12 +19,12 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.fasterxml.jackson.core jackson-databind - ${jackson.databind.version} + ${jackson.version} @@ -48,7 +48,5 @@ 1.8 1.8 5.4.0.Final - 1.4.197 - 2.9.8 \ 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/README.md b/core-java-modules/core-java-security/README.md index 9526b15be5..a833ca30bb 100644 --- a/core-java-modules/core-java-security/README.md +++ b/core-java-modules/core-java-security/README.md @@ -10,3 +10,4 @@ - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) - [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) +- [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random) 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-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java new file mode 100644 index 0000000000..d73f2a2708 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java @@ -0,0 +1,29 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.RealmCallback; + +public class ClientCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java new file mode 100644 index 0000000000..3e071d68cc --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.AuthorizeCallback; +import javax.security.sasl.RealmCallback; + +public class ServerCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof AuthorizeCallback) { + AuthorizeCallback ac = (AuthorizeCallback) cb; + ac.setAuthorized(true); + } else if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java new file mode 100644 index 0000000000..6601654781 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.sasl; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SaslUnitTest { + + private static final String MECHANISM = "DIGEST-MD5"; + private static final String SERVER_NAME = "myServer"; + private static final String PROTOCOL = "myProtocol"; + private static final String AUTHORIZATION_ID = null; + private static final String QOP_LEVEL = "auth-conf"; + + private SaslServer saslServer; + private SaslClient saslClient; + + @Before + public void setUp() throws SaslException { + + ServerCallbackHandler serverHandler = new ServerCallbackHandler(); + ClientCallbackHandler clientHandler = new ClientCallbackHandler(); + + Map props = new HashMap<>(); + props.put(Sasl.QOP, QOP_LEVEL); + + saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler); + saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler); + + } + + @Test + public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException { + + byte[] challenge; + byte[] response; + + challenge = saslServer.evaluateResponse(new byte[0]); + response = saslClient.evaluateChallenge(challenge); + + challenge = saslServer.evaluateResponse(response); + response = saslClient.evaluateChallenge(challenge); + + assertTrue(saslServer.isComplete()); + assertTrue(saslClient.isComplete()); + + String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP); + assertEquals("auth-conf", qop); + + byte[] outgoing = "Baeldung".getBytes(); + byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length); + + byte[] secureIncoming = secureOutgoing; + byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length); + assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8)); + } + + @After + public void tearDown() throws SaslException { + saslClient.dispose(); + saslServer.dispose(); + } + +} 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 2f33212c38..2a2cb3a6af 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -113,7 +113,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -453,8 +453,6 @@ 2.8.2 - 3.9 - 2.5 3.6.1 1.0.3 0.4 @@ -471,7 +469,6 @@ 2.21.0 1.1 - 1.4.197 2.1.0.1 1.19 diff --git a/core-java-modules/multimodulemavenproject/README.md b/core-java-modules/multimodulemavenproject/README.md new file mode 100644 index 0000000000..fc4ca60b6b --- /dev/null +++ b/core-java-modules/multimodulemavenproject/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 11a1003460..ecf1f4147e 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -17,6 +17,8 @@ pre-jpms core-java-exceptions core-java-optional + core-java-lang-operators + core-java-networking-2 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/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/data-structures/README.md b/data-structures/README.md index 2d92068390..5ea9657173 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -1,4 +1,5 @@ ## Relevant articles: -[The Trie Data Structure in Java](https://www.baeldung.com/trie-java) -[Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree) +- [The Trie Data Structure in Java](https://www.baeldung.com/trie-java) +- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree) +- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search) diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java new file mode 100644 index 0000000000..40df2c713a --- /dev/null +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -0,0 +1,74 @@ +package com.baeldung.graph; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Stack; + +public class Graph { + + private Map> adjVertices; + + public Graph() { + this.adjVertices = new HashMap>(); + } + + public void addVertex(int vertex) { + adjVertices.putIfAbsent(vertex, new ArrayList<>()); + } + + public void addEdge(int src, int dest) { + adjVertices.get(src).add(dest); + } + + public void dfsWithoutRecursion(int start) { + Stack stack = new Stack(); + boolean[] isVisited = new boolean[adjVertices.size()]; + stack.push(start); + while (!stack.isEmpty()) { + int current = stack.pop(); + isVisited[current] = true; + visit(current); + for (int dest : adjVertices.get(current)) { + if (!isVisited[dest]) + stack.push(dest); + } + } + } + + public void dfs(int start) { + boolean[] isVisited = new boolean[adjVertices.size()]; + dfsRecursive(start, isVisited); + } + + private void dfsRecursive(int current, boolean[] isVisited) { + isVisited[current] = true; + visit(current); + for (int dest : adjVertices.get(current)) { + if (!isVisited[dest]) + dfsRecursive(dest, isVisited); + } + } + + public List topologicalSort(int start) { + LinkedList result = new LinkedList(); + boolean[] isVisited = new boolean[adjVertices.size()]; + topologicalSortRecursive(start, isVisited, result); + return result; + } + + private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList result) { + isVisited[current] = true; + for (int dest : adjVertices.get(current)) { + if (!isVisited[dest]) + topologicalSortRecursive(dest, isVisited, result); + } + result.addFirst(current); + } + + private void visit(int value) { + System.out.print(" " + value); + } +} diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index f435e41afa..bb62714006 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -2,6 +2,7 @@ package com.baeldung.tree; import java.util.LinkedList; import java.util.Queue; +import java.util.Stack; public class BinaryTree { @@ -102,14 +103,14 @@ public class BinaryTree { public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); - System.out.print(" " + node.value); + visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { - System.out.print(" " + node.value); + visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } @@ -119,7 +120,7 @@ public class BinaryTree { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); - System.out.print(" " + node.value); + visit(node.value); } } @@ -147,6 +148,71 @@ public class BinaryTree { } } + + public void traverseInOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + while(current.left != null) { + current = current.left; + stack.push(current); + } + current = stack.pop(); + visit(current.value); + if(current.right != null) { + current = current.right; + stack.push(current); + } + } + } + + public void traversePreOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + current = stack.pop(); + visit(current.value); + + if(current.right != null) + stack.push(current.right); + + if(current.left != null) + stack.push(current.left); + } + } + + public void traversePostOrderWithoutRecursion() { + Stack stack = new Stack(); + Node prev = root; + Node current = root; + stack.push(root); + + while (!stack.isEmpty()) { + current = stack.peek(); + boolean hasChild = (current.left != null || current.right != null); + boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); + + if (!hasChild || isPrevLastChild) { + current = stack.pop(); + visit(current.value); + prev = current; + } else { + if (current.right != null) { + stack.push(current.right); + } + if (current.left != null) { + stack.push(current.left); + } + } + } + } + + private void visit(int value) { + System.out.print(" " + value); + } + class Node { int value; Node left; diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java new file mode 100644 index 0000000000..09b92115d2 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.graph; + +import java.util.List; + +import org.junit.Test; + +public class GraphUnitTest { + + @Test + public void givenDirectedGraph_whenDFS_thenPrintAllValues() { + Graph graph = createDirectedGraph(); + graph.dfs(0); + System.out.println(); + graph.dfsWithoutRecursion(0); + } + + @Test + public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { + Graph graph = createDirectedGraph(); + List list = graph.topologicalSort(0); + System.out.println(list); + } + + private Graph createDirectedGraph() { + Graph graph = new Graph(); + graph.addVertex(0); + graph.addVertex(1); + graph.addVertex(2); + graph.addVertex(3); + graph.addVertex(4); + graph.addVertex(5); + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + return graph; + } +} diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java index f81247b74d..f99cb52ed7 100644 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -87,6 +87,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); + System.out.println(); + bt.traverseInOrderWithoutRecursion(); } @Test @@ -95,6 +97,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); + System.out.println(); + bt.traversePreOrderWithoutRecursion(); } @Test @@ -103,6 +107,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); + System.out.println(); + bt.traversePostOrderWithoutRecursion(); } @Test 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 f9f951880e..e8b327e35f 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -58,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 d8c233a00e..bb2a58483f 100644 --- a/jackson-2/README.md +++ b/jackson-2/README.md @@ -2,7 +2,7 @@ ## Jackson Cookbooks and Examples -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) +- [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects) 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/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-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/README.md b/java-dates-2/README.md index 35286115d4..b2f8319e58 100644 --- a/java-dates-2/README.md +++ b/java-dates-2/README.md @@ -1,3 +1,4 @@ ## Relevant Articles: - [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar) - [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds) +- [Check If a String Is a Valid Date in Java](https://www.baeldung.com/java-string-valid-date) diff --git a/java-dates/README.md b/java-dates/README.md index 8171e5def9..7da309924d 100644 --- a/java-dates/README.md +++ b/java-dates/README.md @@ -29,3 +29,4 @@ - [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) - [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) - [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) +- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) 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-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/main/java/com/baeldung/binarynumbers/BinaryNumbers.java b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java new file mode 100644 index 0000000000..effdee07ad --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java @@ -0,0 +1,148 @@ +package com.baeldung.binarynumbers; + +public class BinaryNumbers { + + /** + * This method takes a decimal number and convert it into a binary number. + * example:- input:10, output:1010 + * + * @param decimalNumber + * @return binary number + */ + public Integer convertDecimalToBinary(Integer decimalNumber) { + + if (decimalNumber == 0) { + return decimalNumber; + } + + StringBuilder binaryNumber = new StringBuilder(); + + while (decimalNumber > 0) { + + int remainder = decimalNumber % 2; + int result = decimalNumber / 2; + + binaryNumber.append(remainder); + decimalNumber = result; + } + + binaryNumber = binaryNumber.reverse(); + + return Integer.valueOf(binaryNumber.toString()); + } + + /** + * This method takes a binary number and convert it into a decimal number. + * example:- input:101, output:5 + * + * @param binary number + * @return decimal Number + */ + public Integer convertBinaryToDecimal(Integer binaryNumber) { + + Integer result = 0; + Integer base = 1; + + while (binaryNumber > 0) { + + int lastDigit = binaryNumber % 10; + binaryNumber = binaryNumber / 10; + + result += lastDigit * base; + + base = base * 2; + } + return result; + } + + /** + * This method accepts two binary numbers and returns sum of input numbers. + * Example:- firstNum: 101, secondNum: 100, output: 1001 + * + * @param firstNum + * @param secondNum + * @return addition of input numbers + */ + public Integer addBinaryNumber(Integer firstNum, Integer secondNum) { + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || secondNum != 0) { + + temp = (firstNum % 10 + secondNum % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + secondNum % 10 + carry) / 2; + + firstNum = firstNum / 10; + secondNum = secondNum / 10; + } + + if (carry != 0) { + output.append(carry); + } + + return Integer.valueOf(output.reverse() + .toString()); + } + + /** + * This method takes two binary number as input and subtract second number from the first number. + * example:- firstNum: 1000, secondNum: 11, output: 101 + * @param firstNum + * @param secondNum + * @return Result of subtraction of secondNum from first + */ + public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) { + + int onesComplement = Integer.valueOf(getOnesComplement(secondNum)); + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || onesComplement != 0) { + + temp = (firstNum % 10 + onesComplement % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + onesComplement % 10 + carry) / 2; + + firstNum = firstNum / 10; + onesComplement = onesComplement / 10; + } + + String additionOfFirstNumAndOnesComplement = output.reverse() + .toString(); + + if (carry == 1) { + return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry); + } else { + return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement)); + } + + } + + public Integer getOnesComplement(Integer num) { + + StringBuilder onesComplement = new StringBuilder(); + + while (num > 0) { + int lastDigit = num % 10; + if (lastDigit == 0) { + onesComplement.append(1); + } else { + onesComplement.append(0); + } + num = num / 10; + } + + return Integer.valueOf(onesComplement.reverse() + .toString()); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java new file mode 100644 index 0000000000..ca6022261d --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.binarynumbers; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BinaryNumbersUnitTest { + + private BinaryNumbers binaryNumbers = new BinaryNumbers(); + + @Test + public void given_decimalNumber_then_returnBinaryNumber() { + assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8)); + assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20)); + } + + @Test + public void given_decimalNumber_then_convertToBinaryNumber() { + assertEquals("1000", Integer.toBinaryString(8)); + assertEquals("10100", Integer.toBinaryString(20)); + } + + @Test + public void given_binaryNumber_then_ConvertToDecimalNumber() { + assertEquals(8, Integer.parseInt("1000", 2)); + assertEquals(20, Integer.parseInt("10100", 2)); + } + + @Test + public void given_binaryNumber_then_returnDecimalNumber() { + assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000)); + assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100)); + } + + @Test + public void given_twoBinaryNumber_then_returnAddition() { + // adding 4 and 10 + assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010)); + + // adding 26 and 14 + assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110)); + } + + @Test + public void given_twoBinaryNumber_then_returnSubtraction() { + // subtracting 16 from 25 + assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000)); + + // subtracting 29 from 16, the output here is negative + assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101)); + } + + @Test + public void given_binaryLiteral_thenReturnDecimalValue() { + + byte five = 0b101; + assertEquals((byte) 5, five); + + short three = 0b11; + assertEquals((short) 3, three); + + int nine = 0B1001; + assertEquals(9, nine); + + long twentyNine = 0B11101; + assertEquals(29, twentyNine); + + int minusThirtySeven = -0B100101; + assertEquals(-37, minusThirtySeven); + + } + +} 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/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 deleted file mode 100644 index 6548c48f2c..0000000000 --- a/java-strings-2/README.MD +++ /dev/null @@ -1,6 +0,0 @@ -## Relevant Articles - -- [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) diff --git a/java-strings-2/README.md b/java-strings-2/README.md new file mode 100644 index 0000000000..55760bfac7 --- /dev/null +++ b/java-strings-2/README.md @@ -0,0 +1,25 @@ +## Relevant Articles: + +- [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) +- [Java – Generate Random String](http://www.baeldung.com/java-random-string) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) +- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) +- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) +- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) +- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) +- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) +- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) +- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) +- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml index 7342953d15..be47b1ec89 100755 --- a/java-strings-2/pom.xml +++ b/java-strings-2/pom.xml @@ -40,6 +40,16 @@ commons-lang3 ${commons-lang3.version} + + commons-io + commons-io + ${commons-io.version} + + + commons-codec + commons-codec + ${commons-codec.version} + junit junit @@ -52,32 +62,54 @@ ${org.hamcrest.version} test + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.passay + passay + ${passay.version} + org.apache.commons commons-text ${commons-text.version} + + com.vdurmont + emoji-java + ${emoji-java.version} + + + org.ahocorasick + ahocorasick + ${ahocorasick.version} + javax.validation validation-api - 2.0.0.Final + ${validation-api.version} org.hibernate.validator hibernate-validator - 6.0.2.Final + ${hibernate-validator.version} javax.el javax.el-api - 3.0.0 + ${javax.el-api.version} org.glassfish.web javax.el - 2.2.6 + ${javax.el.version} - @@ -105,9 +137,19 @@ 3.8.1 + 1.10 + 1.3.1 + + 3.6.1 + 4.0.0 + 0.4.0 61.1 28.0-jre 1.4 + 2.0.0.Final + 6.0.2.Final + 3.0.0 + 2.2.6 \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/MatchWords.java rename to java-strings-2/src/main/java/com/baeldung/string/MatchWords.java diff --git a/java-strings/src/main/java/com/baeldung/string/Pangram.java b/java-strings-2/src/main/java/com/baeldung/string/Pangram.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Pangram.java rename to java-strings-2/src/main/java/com/baeldung/string/Pangram.java diff --git a/java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java b/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java rename to java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java rename to java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java rename to java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java rename to java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java new file mode 100644 index 0000000000..c395b61068 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToLowerCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java new file mode 100644 index 0000000000..1807f854b2 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToUpperCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignLowercase = "\u0069"; + + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignLowercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java 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/java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java new file mode 100644 index 0000000000..9abb7ac453 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.string.todouble; + +import static org.junit.Assert.assertEquals; + +import java.text.DecimalFormat; +import java.text.ParseException; + +import org.junit.Test; + +public class StringToDoubleConversionUnitTest { + + @Test + public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.parseDouble("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() { + Double.parseDouble(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() { + Double.parseDouble("&"); + } + + @Test + public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.valueOf("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() { + Double.valueOf(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() { + Double.valueOf("&"); + } + + @Test + public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException { + assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse(null); + } + + @Test(expected = ParseException.class) + public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse("&"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java diff --git a/java-strings/src/test/resources/test_image.jpg b/java-strings-2/src/test/resources/test_image.jpg similarity index 100% rename from java-strings/src/test/resources/test_image.jpg rename to java-strings-2/src/test/resources/test_image.jpg diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md new file mode 100644 index 0000000000..d909f171a7 --- /dev/null +++ b/java-strings-ops/README.md @@ -0,0 +1,22 @@ +========= + +## Java Strings Cookbooks and Examples + +### Relevant Articles: +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Java String Conversions](https://www.baeldung.com/java-string-conversions) +- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) +- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Split a String in Java](http://www.baeldung.com/java-split-string) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) +- [Java toString() Method](https://www.baeldung.com/java-tostring) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) \ No newline at end of file diff --git a/java-strings-ops/pom.xml b/java-strings-ops/pom.xml new file mode 100644 index 0000000000..b6a7ea2728 --- /dev/null +++ b/java-strings-ops/pom.xml @@ -0,0 +1,99 @@ + + 4.0.0 + com.baeldung + java-strings-ops + 0.1.0-SNAPSHOT + jar + java-strings-ops + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + com.google.guava + guava + ${guava.version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + java-strings-ops + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + -parameters + + + + + + + + 3.8.1 + + 3.6.1 + 27.0.1-jre + 5.3.1 + + + diff --git a/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java rename to java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java diff --git a/java-strings/src/main/java/com/baeldung/string/Palindrome.java b/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Palindrome.java rename to java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringHelper.java b/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringHelper.java rename to java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Customer.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Order.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java diff --git a/JGit/src/main/resources/logback.xml b/java-strings-ops/src/main/resources/logback.xml similarity index 100% rename from JGit/src/main/resources/logback.xml rename to java-strings-ops/src/main/resources/logback.xml diff --git a/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/README.md b/java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/README.md rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/spring-security-mvc-session/.gitignore b/java-strings-ops/src/test/resources/.gitignore similarity index 100% rename from spring-security-mvc-session/.gitignore rename to java-strings-ops/src/test/resources/.gitignore diff --git a/java-strings/README.md b/java-strings/README.md index b342f53918..ef536b4099 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -6,51 +6,18 @@ - [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) - [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) -- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) -- [Java – Generate Random String](http://www.baeldung.com/java-random-string) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) -- [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) -- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) -- [Split a String in Java](http://www.baeldung.com/java-split-string) -- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) -- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) -- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) -- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) -- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) -- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) - [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) - [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) -- [Get Substring from String in Java](https://www.baeldung.com/java-substring) - [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) -- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) -- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) -- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) -- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) -- [Java toString() Method](https://www.baeldung.com/java-tostring) -- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) -- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) -- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) \ No newline at end of file diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 7f66b95355..42a57bfb42 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -62,12 +62,6 @@ guava ${guava.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - org.junit.jupiter @@ -83,24 +77,6 @@ test - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - @@ -134,11 +110,8 @@ 3.6.1 61.1 27.0.1-jre - 4.0.0 5.3.1 - 1.3.1 1.4 - 0.4.0 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/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java new file mode 100644 index 0000000000..b4d80db0ab --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java @@ -0,0 +1,57 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping") +public class MyHttpServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter writer = response.getWriter(); + writer.println(request.getParameter("function")); + if ("getContextPath".equals(request.getParameter("function"))) { + writer.println(request.getContextPath()); + } else if ("getLocalAddr".equals(request.getParameter("function"))) { + writer.println(request.getLocalAddr()); + } else if ("getLocalName".equals(request.getParameter("function"))) { + writer.println(request.getLocalName()); + } else if ("getLocalAPort".equals(request.getParameter("function"))) { + writer.println(request.getLocalPort()); + } else if ("getMethod".equals(request.getParameter("function"))) { + writer.println(request.getMethod()); + } else if ("getParameterNames".equals(request.getParameter("function"))) { + writer.println(request.getParameterNames()); + } else if ("getPathInfo".equals(request.getParameter("function"))) { + writer.println(request.getPathInfo()); + } else if ("getProtocol".equals(request.getParameter("function"))) { + writer.println(request.getProtocol()); + } else if ("getQueryString".equals(request.getParameter("function"))) { + writer.println(request.getQueryString()); + } else if ("getRequestedSessionId".equals(request.getParameter("function"))) { + writer.println(request.getRequestedSessionId()); + } else if ("getRequestURI".equals(request.getParameter("function"))) { + writer.println(request.getRequestURI()); + } else if ("getRequestURL".equals(request.getParameter("function"))) { + writer.println(request.getRequestURL()); + } else if ("getScheme".equals(request.getParameter("function"))) { + writer.println(request.getScheme()); + } else if ("getServerName".equals(request.getParameter("function"))) { + writer.println(request.getServerName()); + } else if ("getServerPort".equals(request.getParameter("function"))) { + writer.println(request.getServerPort()); + } else if ("getServletPath".equals(request.getParameter("function"))) { + writer.println(request.getServletPath()); + } else { + writer.println("INVALID FUNCTION"); + } + writer.flush(); + } + +} + + diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java new file mode 100644 index 0000000000..6df1b79a60 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java @@ -0,0 +1,19 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import java.math.BigDecimal; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.Digits; + +public class Invoice { + + @DecimalMin(value = "0.0", inclusive = false) + @Digits(integer=3, fraction=2) + private BigDecimal price; + private String description; + + public Invoice(BigDecimal price, String description) { + this.price = price; + this.description = description; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java new file mode 100644 index 0000000000..525dd7d1ad --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java @@ -0,0 +1,62 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class InvoiceUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIsZero_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0")); + } + + @Test + public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + +} 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/pom.xml b/jee-kotlin/pom.xml index 963c03d0df..17163ba23c 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -2,43 +2,16 @@ 4.0.0 + jee-kotlin + jee-kotlin + war + parent-modules com.baeldung 1.0.0-SNAPSHOT - jee-kotlin - jee-kotlin - war - - - UTF-8 - false - 8.0 - - - 1.3.41 - official - true - - - 8.2.1.Final - 3.2.3 - 2.21.0 - 3.1.1 - - 1.4.1.Final - 2.0.1.Final - 1.0.0.Alpha4 - - 4.12 - 3.8.0.Final - 2.9.8 - 3.1.3 - - - org.jetbrains.kotlin @@ -134,7 +107,7 @@ org.apache.maven.plugins maven-war-plugin - ${mvn-war-plugin.version} + ${maven-war-plugin.version} webapp kotlin @@ -286,4 +259,28 @@ + + + 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/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/JGit/README.md b/jgit/README.md similarity index 100% rename from JGit/README.md rename to jgit/README.md diff --git a/JGit/pom.xml b/jgit/pom.xml similarity index 100% rename from JGit/pom.xml rename to jgit/pom.xml diff --git a/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java rename to jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/OpenRepository.java rename to jgit/src/main/java/com/baeldung/jgit/OpenRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/helper/Helper.java rename to jgit/src/main/java/com/baeldung/jgit/helper/Helper.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java rename to jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java rename to jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java rename to jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java rename to jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java diff --git a/Twitter4J/src/main/resources/logback.xml b/jgit/src/main/resources/logback.xml similarity index 100% rename from Twitter4J/src/main/resources/logback.xml rename to jgit/src/main/resources/logback.xml diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java rename to jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java 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/jhipster/jhipster-microservice/README.md b/jhipster/jhipster-microservice/README.md new file mode 100644 index 0000000000..7abe3204c4 --- /dev/null +++ b/jhipster/jhipster-microservice/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index a2c267b74d..65cc51ad88 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,4 +1,6 @@ -### Relevant articles +## Relevant Articles + +- [Intro to JHipster](https://www.baeldung.com/jhipster) # baeldung diff --git a/jhipster/jhipster-uaa/README.md b/jhipster/jhipster-uaa/README.md new file mode 100644 index 0000000000..3971e3c8c6 --- /dev/null +++ b/jhipster/jhipster-uaa/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) 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 6bc790e7ee..5c19c887d3 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -83,7 +83,6 @@ 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/libraries-2/README.md b/libraries-2/README.md index 1b042ac3c5..400aa475d1 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -1,5 +1,4 @@ - -### Relevant Articles: +## Relevant Articles: - [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java) - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) @@ -8,3 +7,7 @@ - [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) +- [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) +- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) +- [Guide to MapDB](https://www.baeldung.com/mapdb) +- [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) 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-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/README.md b/libraries-server/README.md index dc6bcd0716..b5392f5883 100644 --- a/libraries-server/README.md +++ b/libraries-server/README.md @@ -1,4 +1,4 @@ -### Relevant articles +## Relevant Articles: - [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded) - [Introduction to Netty](http://www.baeldung.com/netty) @@ -8,3 +8,4 @@ - [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) - [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) - [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client) +- [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd) 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 f6f2cf4e07..649e83177b 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -42,7 +42,6 @@ - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Introduction to Smooks](http://www.baeldung.com/smooks) - [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) @@ -53,7 +52,6 @@ - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) -- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) diff --git a/libraries/pom.xml b/libraries/pom.xml index 8e787bdc22..e8ffde5f99 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -45,7 +45,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} commons-net @@ -818,7 +818,6 @@ 0.1.0 0.7.0 3.2.7 - 3.6 1.9.2 1.2 3.21.0-GA @@ -826,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 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/pom.xml b/maven/pom.xml index 96643d76f3..ef6e7b7d93 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -299,7 +299,6 @@ - 1.8 3.0.2 3.8.0 2.22.0 @@ -310,6 +309,5 @@ Baeldung 9.4.11.v20180605 2.27 - 4.12 \ No newline at end of file diff --git a/morphia/README.md b/morphia/README.md deleted file mode 100644 index 008cf76c49..0000000000 --- a/morphia/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to Morphia](http://www.baeldung.com/intro-to-morphia) diff --git a/morphia/pom.xml b/morphia/pom.xml deleted file mode 100644 index e4010a26a1..0000000000 --- a/morphia/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - com.baeldung.morphia - morphia - morphia - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - - dev.morphia.morphia - core - ${morphia.version} - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - - - - 1.4.2.RELEASE - 1.5.3 - - - 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 index 10e78a2dfd..ba5e1ec359 100644 --- 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 @@ -121,8 +121,8 @@ public class AuthorizationEndpoint { String redirectUri = originalParams.getFirst("resolved_redirect_uri"); StringBuilder sb = new StringBuilder(redirectUri); - String approbationStatus = params.getFirst("approbation_status"); - if ("NO".equals(approbationStatus)) { + String approvalStatus = params.getFirst("approval_status"); + if ("NO".equals(approvalStatus)) { URI location = UriBuilder.fromUri(sb.toString()) .queryParam("error", "User doesn't approved the request.") .queryParam("error_description", "User doesn't approved the request.") 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 index f39bb2ea2d..0ea12da16e 100644 --- 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 @@ -15,15 +15,14 @@ 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.Arrays; 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"); + List supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token"); @Inject private AppDataRepository appDataRepository; @@ -39,36 +38,36 @@ public class TokenEndpoint { //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(); + if (grantType == null || grantType.isEmpty()) + return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST); + if (!supportedGrantTypes.contains(grantType)) { + return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST); } //Client Authentication String[] clientCredentials = extract(authHeader); + if (clientCredentials.length != 2) { + return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST); + } 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(); + if (client == null) { + return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST); + } + String clientSecret = clientCredentials[1]; + if (!clientSecret.equals(client.getClientSecret())) { + return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED); } AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); JsonObject tokenResponse = null; try { tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (WebApplicationException e) { + return e.getResponse(); } catch (Exception e) { - e.printStackTrace(); + return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok(tokenResponse) @@ -81,6 +80,15 @@ public class TokenEndpoint { if (authHeader != null && authHeader.startsWith("Basic ")) { return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); } - return null; + return new String[]{}; + } + + private Response responseError(String error, String errorDescription, Response.Status status) { + JsonObject errorResponse = Json.createObjectBuilder() + .add("error", error) + .add("error_description", errorDescription) + .build(); + return Response.status(status) + .entity(errorResponse).build(); } } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java new file mode 100644 index 0000000000..324bacb33f --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java @@ -0,0 +1,87 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.crypto.RSASSAVerifier; +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 java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler { + + //Always RSA 256, but could be parametrized + protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + @Inject + protected Config config; + + //30 min + protected Long expiresInMin = 30L; + + protected JWSVerifier getJWSVerifier() throws Exception { + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return new RSASSAVerifier(rsaPublicKey); + } + + protected JWSSigner getJwsSigner() throws Exception { + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + return new RSASSASigner(rsaKey.toRSAPrivateKey()); + } + + protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception { + //4. Signing + JWSSigner jwsSigner = getJwsSigner(); + + Instant now = Instant.now(); + //Long expiresInMin = 30L; + Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(subject) + .claim("upn", subject) + .claim("client_id", clientId) + .audience("http://localhost:9280") + .claim("scope", approvedScope) + .claim("groups", Arrays.asList(approvedScope.split(" "))) + .expirationTime(expirationTime) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + signedJWT.sign(jwsSigner); + return signedJWT.serialize(); + } + + protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception { + JWSSigner jwsSigner = getJwsSigner(); + Instant now = Instant.now(); + //6.Build refresh token + JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder() + .subject(subject) + .claim("client_id", clientId) + .claim("scope", approvedScope) + //refresh token for 1 day. + .expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS))) + .build(); + SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims); + signedRefreshToken.sign(jwsSigner); + return signedRefreshToken.serialize(); + } +} 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 index 889c7fcea2..78128aead6 100644 --- 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 @@ -1,18 +1,7 @@ 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; @@ -20,22 +9,14 @@ 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 { +public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler { @PersistenceContext private EntityManager entityManager; - @Inject - private Config config; - @Override public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { //1. code is required @@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType 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(); + String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); + String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) .add("scope", authorizationCode.getApprovedScopes()) + .add("refresh_token", refreshToken) .build(); } } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java new file mode 100644 index 0000000000..63e3552353 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -0,0 +1,72 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jwt.SignedJWT; + +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +@Named("refresh_token") +public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + String refreshToken = params.getFirst("refresh_token"); + if (refreshToken == null || "".equals(refreshToken)) { + throw new WebApplicationException("invalid_grant"); + } + + //Decode refresh token + SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken); + JWSVerifier verifier = getJWSVerifier(); + + if (!signedRefreshToken.verify(verifier)) { + throw new WebApplicationException("Invalid refresh token."); + } + if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) { + throw new WebApplicationException("Refresh token expired."); + } + String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id"); + if (!clientId.equals(refreshTokenClientId)) { + throw new WebApplicationException("Invalid client_id."); + } + + //At this point, the refresh token is valid and not yet expired + //So create a new access token from it. + String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); + String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); + + String requestedScopes = params.getFirst("scope"); + if (requestedScopes != null && !requestedScopes.isEmpty()) { + Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); + Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); + if (!aScopes.containsAll(rScopes)) { + JsonObject error = Json.createObjectBuilder() + .add("error", "Invalid_request") + .add("error_description", "Requested scopes should be a subset of the original scopes.") + .build(); + Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build(); + throw new WebApplicationException(response); + } + } else { + requestedScopes = approvedScopes; + } + + String accessToken = getAccessToken(clientId, subject, requestedScopes); + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", requestedScopes) + .add("refresh_token", refreshToken) + .build(); + } +} 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 deleted file mode 100644 index 84b9a89c54..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java +++ /dev/null @@ -1,209 +0,0 @@ -//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 deleted file mode 100644 index 73085a68d1..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java +++ /dev/null @@ -1,70 +0,0 @@ -//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/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp index 1004b5b8b7..41b0582c03 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -41,8 +41,8 @@ - - + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java new file mode 100644 index 0000000000..7059c4f7e1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java @@ -0,0 +1,23 @@ +package com.baeldung.oauth2.client; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Base64; + +public abstract class AbstractServlet extends HttpServlet { + + protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + protected String getAuthorizationHeaderValue(String clientId, String clientSecret) { + 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/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java index 87aa8bc668..e72877076c 100644 --- 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 @@ -4,10 +4,8 @@ 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; @@ -18,10 +16,9 @@ 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 { +public class CallbackServlet extends AbstractServlet { @Inject private Config config; @@ -29,6 +26,9 @@ public class CallbackServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + //Error: String error = request.getParameter("error"); if (error != null) { @@ -53,24 +53,15 @@ public class CallbackServlet extends HttpServlet { 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); + try { + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + request.getSession().setAttribute("tokenResponse", tokenResponse); + } catch (Exception ex) { + System.out.println(ex.getMessage()); + request.setAttribute("error", ex.getMessage()); + } 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/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java new file mode 100644 index 0000000000..a519a53070 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -0,0 +1,57 @@ +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.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 javax.ws.rs.core.Response; +import java.io.IOException; + +@WebServlet(urlPatterns = "/refreshtoken") +public class RefreshTokenServlet extends AbstractServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + + JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "refresh_token"); + form.param("refresh_token", actualTokenResponse.getString("refresh_token")); + + String scope = request.getParameter("scope"); + if (scope != null && !scope.isEmpty()) { + form.param("scope", scope); + } + + Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); + JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); + if (jaxrsResponse.getStatus() == 200) { + request.getSession().setAttribute("tokenResponse", tokenResponse); + } else { + request.setAttribute("error", tokenResponse.getString("error_description", "error!")); + } + dispatch("/", request, response); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp index 23fec70f33..ccb74df228 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -10,6 +10,7 @@ body { margin: 0px; } + input[type=text], input[type=password] { width: 75%; padding: 4px 0px; @@ -17,6 +18,7 @@ border: 1px solid #502bcc; box-sizing: border-box; } + .container-error { padding: 16px; border: 1px solid #cc102a; @@ -25,6 +27,7 @@ margin-left: 25px; margin-bottom: 25px; } + .container { padding: 16px; border: 1px solid #130ecc; @@ -81,8 +84,20 @@
  • access_token: ${tokenResponse.getString("access_token")}
  • scope: ${tokenResponse.getString("scope")}
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
  • refresh_token: ${tokenResponse.getString("refresh_token")}
  • + + +

    OAuth2 Resource Server Call


    @@ -90,7 +105,6 @@
  • Read Protected Resource
  • Write Protected Resource
  • -
    diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md deleted file mode 100644 index fce9e101da..0000000000 --- a/parent-boot-performance/README.md +++ /dev/null @@ -1 +0,0 @@ -This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml deleted file mode 100644 index b7d12e2ba4..0000000000 --- a/parent-boot-performance/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - parent-boot-performance - 0.0.1-SNAPSHOT - parent-boot-performance - pom - Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - io.rest-assured - rest-assured - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - thin-jar - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot.experimental - spring-boot-thin-layout - ${thin.version} - - - - - - - - - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - - diff --git a/parent-java/README.md b/parent-java/README.md index ff12555376..729105e3fd 100644 --- a/parent-java/README.md +++ b/parent-java/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: diff --git a/parent-spring-4/README.md b/parent-spring-4/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-4/README.md +++ b/parent-spring-4/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: 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/README.md b/parent-spring-5/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-5/README.md +++ b/parent-spring-5/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: 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/backoff-jitter/README.md b/patterns/backoff-jitter/README.md new file mode 100644 index 0000000000..6459e4c8e0 --- /dev/null +++ b/patterns/backoff-jitter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Better Retries with Exponential Backoff and Jitter](https://baeldung.com/retries-with-exponential-backoff-and-jitter) diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml new file mode 100644 index 0000000000..6b0d016609 --- /dev/null +++ b/patterns/backoff-jitter/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.baeldung + backoff-jitter + 1.0.0-SNAPSHOT + pom + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + test + + + org.slf4j + slf4j-simple + ${slf4j.version} + test + + + + + UTF-8 + 1.8 + 1.8 + 4.12 + 2.27.0 + 1.7.26 + 0.16.0 + + + \ No newline at end of file diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java new file mode 100644 index 0000000000..f6b3ebbe45 --- /dev/null +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -0,0 +1,103 @@ +package com.baeldung.backoff.jitter; + +import io.github.resilience4j.retry.IntervalFunction; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; + +import static com.baeldung.backoff.jitter.BackoffWithJitterTest.RetryProperties.*; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialBackoff; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialRandomBackoff; +import static java.util.Collections.nCopies; +import static java.util.concurrent.Executors.newFixedThreadPool; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +public class BackoffWithJitterTest { + + static Logger log = LoggerFactory.getLogger(BackoffWithJitterTest.class); + + interface PingPongService { + + String call(String ping) throws PingPongServiceException; + } + + class PingPongServiceException extends RuntimeException { + + public PingPongServiceException(String reason) { + super(reason); + } + } + + private PingPongService service; + private static final int NUM_CONCURRENT_CLIENTS = 8; + + @Before + public void setUp() { + service = mock(PingPongService.class); + } + + @Test + public void whenRetryExponentialBackoff_thenRetriedConfiguredNoOfTimes() { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + Function pingPongFn = getRetryablePingPongFn(intervalFn); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + try { + pingPongFn.apply("Hello"); + } catch (PingPongServiceException e) { + verify(service, times(MAX_RETRIES)).call(anyString()); + } + } + + @Test + public void whenRetryExponentialBackoffWithoutJitter_thenThunderingHerdProblemOccurs() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + test(intervalFn); + } + + @Test + public void whenRetryExponentialBackoffWithJitter_thenRetriesAreSpread() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialRandomBackoff(INITIAL_INTERVAL, MULTIPLIER, RANDOMIZATION_FACTOR); + test(intervalFn); + } + + private void test(IntervalFunction intervalFn) throws InterruptedException { + Function pingPongFn = getRetryablePingPongFn(intervalFn); + ExecutorService executors = newFixedThreadPool(NUM_CONCURRENT_CLIENTS); + List> tasks = nCopies(NUM_CONCURRENT_CLIENTS, () -> pingPongFn.apply("Hello")); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + + executors.invokeAll(tasks); + } + + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { + RetryConfig retryConfig = RetryConfig.custom() + .maxAttempts(MAX_RETRIES) + .intervalFunction(intervalFn) + .retryExceptions(PingPongServiceException.class) + .build(); + Retry retry = Retry.of("pingpong", retryConfig); + return Retry.decorateFunction(retry, ping -> { + log.info("Invoked at {}", LocalDateTime.now()); + return service.call(ping); + }); + } + + static class RetryProperties { + static final Long INITIAL_INTERVAL = 1000L; + static final Double MULTIPLIER = 2.0D; + static final Double RANDOMIZATION_FACTOR = 0.6D; + static final Integer MAX_RETRIES = 4; + } +} 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/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/pom.xml b/patterns/pom.xml index 875af67d55..7f7368ca07 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -19,7 +19,8 @@ design-patterns design-patterns-2 solid - dip + dip + backoff-jitter @@ -51,7 +52,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/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 0df13653b9..99374f9135 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -4,3 +4,4 @@ - [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 509c54ca75..e90d7463bd 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -58,7 +58,7 @@ hibernate-mapping - src/test/resources + src/main/resources true 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/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 708d2b3c76..e7c93bc4e5 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -4,7 +4,7 @@ com.baeldung java-cassandra 1.0.0-SNAPSHOT - java-cassandra + java-cassandra com.baeldung @@ -29,6 +29,19 @@ ${cassandra-unit.version} + + + com.datastax.oss + java-driver-core + ${datastax-cassandra.version} + + + + io.netty + netty-handler + ${io-netty.version} + + @@ -39,6 +52,8 @@ 3.1.2 3.1.1.0 + 4.1.0 + 4.1.34.Final 18.0
    diff --git a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java new file mode 100644 index 0000000000..23140e0455 --- /dev/null +++ b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java @@ -0,0 +1,46 @@ +package com.baeldung.datastax.cassandra; + +import com.baeldung.datastax.cassandra.domain.Video; +import com.baeldung.datastax.cassandra.repository.KeyspaceRepository; +import com.baeldung.datastax.cassandra.repository.VideoRepository; +import com.datastax.oss.driver.api.core.CqlSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; + +public class Application { + + private static final Logger LOG = LoggerFactory.getLogger(Application.class); + + public static void main(String[] args) { + new Application().run(); + } + + public void run() { + CassandraConnector connector = new CassandraConnector(); + connector.connect("127.0.0.1", 9042, "datacenter1"); + CqlSession session = connector.getSession(); + + KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session); + + keyspaceRepository.createKeyspace("testKeyspace", "SimpleStrategy", 1); + keyspaceRepository.useKeyspace("testKeyspace"); + + VideoRepository videoRepository = new VideoRepository(session); + + videoRepository.createTable(); + + videoRepository.insertVideo(new Video("Video Title 1", Instant.now())); + videoRepository.insertVideo(new Video("Video Title 2", + Instant.now().minus(1, ChronoUnit.DAYS))); + + List
    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..020e867c82 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,8 +9,8 @@ - [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) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### 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/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index 35e80b81a5..b7cf0fadf2 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -47,7 +47,7 @@ import com.google.common.base.Preconditions; @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 2f23a9a532..444324dafc 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.persistence.audit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.List; @@ -17,6 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +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; @@ -29,6 +31,7 @@ import com.baeldung.spring.config.PersistenceTestConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class EnversFooBarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); 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 f40659bc16..451b5b4961 100644 --- a/pom.xml +++ b/pom.xml @@ -10,10 +10,6 @@ parent-modules pom - - quarkus - - @@ -312,6 +308,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -388,6 +388,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 @@ -461,12 +462,14 @@ java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams java-strings java-strings-2 + java-strings-ops java-vavr-stream java-websocket javafx @@ -477,9 +480,8 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups - jhipster jhipster-5 jib jjwt @@ -506,6 +508,7 @@ libraries-security libraries-server libraries-http + libraries-io linkrest logging-modules lombok @@ -544,7 +547,6 @@ ratpack reactor-core - rest-with-spark-java resteasy restx @@ -557,8 +559,7 @@ tensorflow-java spring-boot-flowable spring-security-kerberos - morphia - + oauth2-framework-impl @@ -575,6 +576,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -607,6 +612,7 @@ 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 @@ -656,22 +662,23 @@ spring-boot-vue spring-boot-libraries - spring-cloud - spring-cloud-bus + + + - spring-cloud-data-flow + spring-core spring-core-2 spring-cucumber spring-data-rest - spring-data-rest-querydsl + spring-dispatcher-servlet spring-drools spring-ehcache - spring-ejb + spring-exceptions spring-freemarker @@ -724,8 +731,6 @@ spring-security-angular/server spring-security-cache-control - spring-security-client - spring-security-core spring-security-mvc-boot spring-security-mvc-custom @@ -734,7 +739,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid @@ -745,7 +750,7 @@ spring-security-stormpath spring-security-thymeleaf spring-security-x509 - spring-session + spring-sleuth spring-soap spring-social-login @@ -756,12 +761,10 @@ spring-thymeleaf - spring-userservice - - spring-vault + spring-vertx - spring-webflux-amqp + spring-zuul @@ -773,11 +776,10 @@ testing-modules twilio - Twitter4J + twitter4j undertow - vavr vertx vertx-and-rxjava video-tutorials @@ -786,13 +788,11 @@ wicket xml - xmlunit-2 xstream tensorflow-java spring-boot-flowable spring-security-kerberos - morphia @@ -823,6 +823,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 @@ -841,7 +842,8 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter - greeter-spring-boot-autoconfigure + spring-boot-di + greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database spring-boot-jasypt @@ -906,14 +908,13 @@ spring-security-acl spring-security-angular spring-security-cache-control - 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-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-rest spring-security-sso @@ -928,7 +929,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 @@ -956,6 +956,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -984,17 +988,19 @@ core-kotlin-io jenkins/hello-world + jhipster jws libraries - persistence-modules/hibernate5 persistence-modules/hibernate-mapping persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql vaadin + vavr @@ -1078,6 +1084,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 @@ -1147,12 +1154,14 @@ java-ee-8-security-api java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams java-strings java-strings-2 + java-strings-ops java-vavr-stream java-websocket javafx @@ -1163,9 +1172,8 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups - jhipster jhipster-5 jib jjwt @@ -1227,7 +1235,6 @@ ratpack reactor-core - rest-with-spark-java resteasy restx @@ -1235,6 +1242,7 @@ rsocket rxjava rxjava-2 + oauth2-framework-impl @@ -1279,6 +1287,7 @@ 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 @@ -1391,9 +1400,6 @@ spring-security-acl spring-security-angular/server spring-security-cache-control - - spring-security-client - spring-security-core spring-security-mvc-boot spring-security-mvc-custom @@ -1401,7 +1407,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid @@ -1423,8 +1429,6 @@ spring-thymeleaf - spring-userservice - spring-vault spring-vertx @@ -1440,11 +1444,10 @@ testing-modules twilio - Twitter4J + twitter4j undertow - vavr vertx vertx-and-rxjava video-tutorials @@ -1453,9 +1456,7 @@ wicket xml - xmlunit-2 xstream - @@ -1496,16 +1497,19 @@ core-kotlin-2 jenkins/hello-world + jhipster jws libraries persistence-modules/hibernate5 persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql vaadin + vavr @@ -1557,6 +1561,7 @@ 2.21.0 2.5 2.6 + 3.5 1.4 3.0.0 3.1.0 @@ -1578,4 +1583,5 @@ 1.16.12 1.4.197 + diff --git a/quarkus/README.md b/quarkus/README.md index 01009eab3e..3ff08c6f9e 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: -- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) +- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) diff --git a/quarkus/pom.xml b/quarkus/pom.xml index d8f274df6d..ceb2e2c0d4 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -7,7 +7,7 @@ 1.0-SNAPSHOT 2.22.0 - 0.13.1 + 0.15.0 1.8 UTF-8 1.8 diff --git a/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java b/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java index 4b19de1b63..4c505fbabe 100644 --- a/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java +++ b/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java @@ -8,7 +8,7 @@ import javax.enterprise.context.ApplicationScoped; public class HelloService { @ConfigProperty(name = "greeting") - private String greeting; + String greeting; public String politeHello(String name){ return greeting + " " + name; diff --git a/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java b/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java similarity index 91% rename from quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java rename to quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java index 3d0fff7562..a5ed99f585 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java @@ -7,7 +7,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @QuarkusTest -public class HelloResourceTest { +public class HelloResourceUnitTest { @Test public void testHelloEndpoint() { diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java index 4b0606f588..9ada64b6a5 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java @@ -3,7 +3,7 @@ package com.baeldung.quarkus; import io.quarkus.test.junit.SubstrateTest; @SubstrateTest -public class NativeHelloResourceIT extends HelloResourceTest { +public class NativeHelloResourceIT extends HelloResourceUnitTest { // Execute the same tests but in native mode. } \ No newline at end of file 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/bin/README.md b/resteasy/bin/README.md deleted file mode 100644 index f4dba1493a..0000000000 --- a/resteasy/bin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -========= - -## A Guide to RESTEasy - - -### Relevant Articles: 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/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/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 056fb37a52..5372803842 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -77,29 +77,34 @@ org.springframework spring-tx - 5.2.0.M2 + ${spring-tx.version} org.springframework.data spring-data-r2dbc - 1.0.0.M2 + ${spring-data-r2dbc.version} io.r2dbc r2dbc-h2 - 0.8.0.M8 + ${r2dbc-h2.version} com.h2database h2 - 1.4.199 + ${h2.version} org.springframework.boot spring-boot-starter-test test + + org.apache.httpcomponents + httpclient + ${httpclient.version} + @@ -195,11 +200,6 @@ - - 1.2.40 - 1.2.40 - - spring-snapshots @@ -216,5 +216,15 @@ + + 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/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/README.md b/spring-5-mvc/README.md index 7e83077f54..063945281f 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) -- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 7b641ffa79..9569d52abf 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -21,10 +21,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - org.springframework.boot - spring-boot-starter-security - org.springframework.boot spring-boot-starter-validation diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 74a348dea6..38b2d943f8 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -1,12 +1,8 @@ package com.baeldung; -import javax.servlet.Filter; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.web.filter.DelegatingFilterProxy; -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { @@ -14,32 +10,4 @@ public class Spring5Application { public static void main(String[] args) { SpringApplication.run(Spring5Application.class, args); } - - public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected String[] getServletMappings() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected javax.servlet.Filter[] getServletFilters() { - DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); - delegateFilterProxy.setTargetBeanName("loggingFilter"); - return new Filter[] { delegateFilterProxy }; - } - } - } diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml index 43c7143e5b..ab4d38ce1c 100644 --- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml @@ -16,14 +16,5 @@ functional / - - loggingFilter - org.springframework.web.filter.DelegatingFilterProxy - - - - loggingFilter - /* - \ No newline at end of file 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..f1407ee1ad --- /dev/null +++ b/spring-5-reactive-2/pom.xml @@ -0,0 +1,61 @@ + + + 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 + + + + com.github.tomakehurst + wiremock-jre8 + ${wiremock.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.webclient.WebClientApplication + JAR + + + + + + + 2.24.0 + + + 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/main/java/com/baeldung/webclient/filter/WebClientFilters.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java new file mode 100644 index 0000000000..c98caf67b4 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java @@ -0,0 +1,57 @@ +package com.baeldung.webclient.filter; + +import java.io.PrintStream; +import java.net.URI; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpMethod; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; + +public class WebClientFilters { + + private static final Logger LOG = LoggerFactory.getLogger(WebClientFilters.class); + + public static ExchangeFilterFunction demoFilter() { + ExchangeFilterFunction filterFunction = (clientRequest, nextFilter) -> { + LOG.info("WebClient fitler executed"); + return nextFilter.exchange(clientRequest); + }; + return filterFunction; + } + + public static ExchangeFilterFunction countingFilter(AtomicInteger getCounter) { + ExchangeFilterFunction countingFilter = (clientRequest, nextFilter) -> { + HttpMethod httpMethod = clientRequest.method(); + if (httpMethod == HttpMethod.GET) { + getCounter.incrementAndGet(); + } + return nextFilter.exchange(clientRequest); + }; + return countingFilter; + } + + public static ExchangeFilterFunction urlModifyingFilter(String version) { + ExchangeFilterFunction urlModifyingFilter = (clientRequest, nextFilter) -> { + String oldUrl = clientRequest.url() + .toString(); + URI newUrl = URI.create(oldUrl + "/" + version); + ClientRequest filteredRequest = ClientRequest.from(clientRequest) + .url(newUrl) + .build(); + return nextFilter.exchange(filteredRequest); + }; + return urlModifyingFilter; + } + + public static ExchangeFilterFunction loggingFilter(PrintStream printStream) { + ExchangeFilterFunction loggingFilter = (clientRequest, nextFilter) -> { + printStream.print("Sending request " + clientRequest.method() + " " + clientRequest.url()); + return nextFilter.exchange(clientRequest); + }; + return loggingFilter; + } + +} 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-2/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java new file mode 100644 index 0000000000..675cd03d10 --- /dev/null +++ b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java @@ -0,0 +1,145 @@ +package com.baeldung.webclient.filter; + +import static com.baeldung.webclient.filter.WebClientFilters.countingFilter; +import static com.baeldung.webclient.filter.WebClientFilters.loggingFilter; +import static com.baeldung.webclient.filter.WebClientFilters.urlModifyingFilter; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Rule; +import org.junit.Test; +import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; +import org.springframework.web.reactive.function.client.WebClient; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +public class FilteredWebClientUnitTest { + + private static final String PATH = "/filter/test"; + + @Rule + public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort() + .dynamicHttpsPort()); + + @Test + public void whenNoUrlModifyingFilter_thenPathUnchanged() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + WebClient webClient = WebClient.create(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + verify(getRequestedFor(urlPathEqualTo(PATH))); + } + + @Test + public void whenUrlModifyingFilter_thenPathModified() { + stubFor(get(urlPathEqualTo(PATH + "/1.0")).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + WebClient webClient = WebClient.builder() + .filter(urlModifyingFilter("1.0")) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + verify(getRequestedFor(urlPathEqualTo(PATH + "/1.0"))); + } + + @Test + public void givenCountingFilter_whenGet_thenIncreaseCounter() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + AtomicInteger counter = new AtomicInteger(10); + + WebClient webClient = WebClient.builder() + .filter(countingFilter(counter)) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(counter.get()).isEqualTo(11); + } + + @Test + public void givenCountingFilter_whenPost_thenDoNotIncreaseCounter() { + stubFor(post(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + AtomicInteger counter = new AtomicInteger(10); + + WebClient webClient = WebClient.builder() + .filter(countingFilter(counter)) + .build(); + String actual = sendPostRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(counter.get()).isEqualTo(10); + } + + @Test + public void testLoggingFilter() throws IOException { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) { + WebClient webClient = WebClient.builder() + .filter(loggingFilter(ps)) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(baos.toString()).isEqualTo("Sending request GET " + getUrl()); + } + } + + @Test + public void testBasicAuthFilter() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("authorized"))); + + WebClient webClient = WebClient.builder() + .filter(ExchangeFilterFunctions.basicAuthentication("user", "password")) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("authorized"); + verify(getRequestedFor(urlPathEqualTo(PATH)).withHeader("Authorization", containing("Basic"))); + } + + private String sendGetRequest(WebClient webClient) { + return webClient.get() + .uri(getUrl()) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String sendPostRequest(WebClient webClient) { + return webClient.post() + .uri(URI.create(getUrl())) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String getUrl() { + return "http://localhost:" + wireMockRule.port() + PATH; + + } + +} diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index f94bd0b0c1..0df2bdd339 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,3 +4,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles + 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/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 6317723467..6887f01753 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -99,7 +99,6 @@ - 1.8 2.2.0.M3 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/README.md b/spring-all/README.md index b5e91d8d60..d3296bd457 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -34,3 +34,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) +- [The Spring @Qualifier Annotation](https://www.baeldung.com/spring-qualifier-annotation) 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-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java similarity index 81% rename from spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-aop/src/test/java/org/baeldung/SpringContextTest.java index 66243ef00d..4d3ed953c4 100644 --- a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java @@ -1,6 +1,5 @@ package org.baeldung; -import org.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -8,7 +7,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-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/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 62a2701dd0..71c46cb7f5 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -44,8 +44,4 @@ - - - 1.8 - 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/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java new file mode 100644 index 0000000000..d4c8010d2b --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java @@ -0,0 +1,20 @@ +package com.baeldung.springbootconfiguration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +@ComponentScan(basePackages = {"com.baeldung.springbootconfiguration.*"}) +@SpringBootConfiguration +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public PersonService personService() { + return new PersonServiceImpl(); + } +} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java new file mode 100644 index 0000000000..4909d957e5 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java @@ -0,0 +1,4 @@ +package com.baeldung.springbootconfiguration; + +public interface PersonService { +} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java new file mode 100644 index 0000000000..9f2af33e8e --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java @@ -0,0 +1,4 @@ +package com.baeldung.springbootconfiguration; + +public class PersonServiceImpl implements PersonService { +} 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/README.md b/spring-boot-data/README.md index 3fd1d17994..6f0b8c8123 100644 --- a/spring-boot-data/README.md +++ b/spring-boot-data/README.md @@ -1,3 +1,5 @@ -### Relevant Articles: +## Relevant Articles: + - [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) +- [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) 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-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-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-2/.gitignore b/spring-boot-mvc-2/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-mvc-2/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-mvc-2/README.md b/spring-boot-mvc-2/README.md new file mode 100644 index 0000000000..a405298cbe --- /dev/null +++ b/spring-boot-mvc-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Functional Controllers in Spring MVC]() \ No newline at end of file diff --git a/spring-boot-mvc-2/pom.xml b/spring-boot-mvc-2/pom.xml new file mode 100644 index 0000000000..18121325a5 --- /dev/null +++ b/spring-boot-mvc-2/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + spring-boot-mvc-2 + spring-boot-mvc-2 + jar + Module For Spring Boot MVC Web Fn + + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.BUILD-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcFnApplication + JAR + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java new file mode 100644 index 0000000000..2a85550bd7 --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java @@ -0,0 +1,74 @@ +package com.baeldung.springbootmvc; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.notFound; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.ctrl.ProductController; +import com.baeldung.springbootmvc.svc.ProductService; + +@SpringBootApplication +public class SpringBootMvcFnApplication { + + private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class); + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcFnApplication.class, args); + } + + @Bean + RouterFunction productListing(ProductController pc, ProductService ps) { + return pc.productListing(ps); + } + + @Bean + RouterFunction allApplicationRoutes(ProductController pc, ProductService ps) { + return route().add(pc.remainingProductRoutes(ps)) + .before(req -> { + LOG.info("Found a route which matches " + req.uri() + .getPath()); + return req; + }) + .after((req, res) -> { + if (res.statusCode() == HttpStatus.OK) { + LOG.info("Finished processing request " + req.uri() + .getPath()); + } else { + LOG.info("There was an error while processing request" + req.uri()); + } + return res; + }) + .onError(Throwable.class, (e, res) -> { + LOG.error("Fatal exception has occurred", e); + return status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + }) + .build() + .and(route(RequestPredicates.all(), req -> notFound().build())); + } + + public static class Error { + private String errorMessage; + + public Error(String message) { + this.errorMessage = message; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + } +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java new file mode 100644 index 0000000000..6a77e72cea --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java @@ -0,0 +1,59 @@ +package com.baeldung.springbootmvc.ctrl; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.ok; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.function.EntityResponse; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.SpringBootMvcFnApplication.Error; +import com.baeldung.springbootmvc.model.Product; +import com.baeldung.springbootmvc.svc.ProductService; + +@Component +public class ProductController { + + public RouterFunction productListing(ProductService ps) { + return route().GET("/product", req -> ok().body(ps.findAll())) + .build(); + } + + public RouterFunction productSearch(ProductService ps) { + return route().nest(RequestPredicates.path("/product"), builder -> { + builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name")))) + .GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id"))))); + }) + .onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.NOT_FOUND) + .build()) + .build(); + } + + public RouterFunction adminFunctions(ProductService ps) { + return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class)))) + .filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build()) + .onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.BAD_REQUEST) + .build()) + .build(); + } + + public RouterFunction remainingProductRoutes(ProductService ps) { + return route().add(productSearch(ps)) + .add(adminFunctions(ps)) + .build(); + } + + private boolean authenticate(ServerRequest req) { + return Boolean.TRUE; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java new file mode 100644 index 0000000000..1213b3c11e --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java @@ -0,0 +1,72 @@ +package com.baeldung.springbootmvc.model; + +public class Product { + private String name; + private double price; + private int id; + + public Product(String name, double price, int id) { + super(); + this.name = name; + this.price = price; + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + long temp; + temp = Double.doubleToLongBits(price); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Product other = (Product) obj; + if (id != other.id) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) + return false; + return true; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java new file mode 100644 index 0000000000..e2d281d54f --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java @@ -0,0 +1,63 @@ +package com.baeldung.springbootmvc.svc; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.baeldung.springbootmvc.model.Product; + +@Service +public class ProductService { + + private final Set products = new HashSet<>(); + + { + products.add(new Product("Book", 23.90, 1)); + products.add(new Product("Pen", 44.34, 2)); + } + + public Product findById(int id) { + return products.stream() + .filter(obj -> obj.getId() == id) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Product findByName(String name) { + return products.stream() + .filter(obj -> obj.getName() + .equalsIgnoreCase(name)) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Set findAll() { + return products; + } + + public Product save(Product product) { + if (StringUtils.isEmpty(product.getName()) || product.getPrice() == 0.0) { + throw new IllegalArgumentException(); + } + int newId = products.stream() + .mapToInt(Product::getId) + .max() + .getAsInt() + 1; + product.setId(newId); + products.add(product); + return product; + } + + public static class ItemNotFoundException extends RuntimeException { + /** + * + */ + private static final long serialVersionUID = 1L; + + public ItemNotFoundException(String msg) { + super(msg); + } + } +} diff --git a/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-mvc-2/src/main/resources/application.properties new file mode 100644 index 0000000000..709574239b --- /dev/null +++ b/spring-boot-mvc-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/morphia/src/main/resources/logback.xml b/spring-boot-mvc-2/src/main/resources/logback.xml similarity index 100% rename from morphia/src/main/resources/logback.xml rename to spring-boot-mvc-2/src/main/resources/logback.xml 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/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/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-performance/pom.xml b/spring-boot-performance/pom.xml index f51df8bc0c..a4efa4a8d7 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -8,10 +8,10 @@ This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 - parent-boot-performance + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-performance + ../parent-boot-2 @@ -42,4 +42,4 @@ com.baeldung.lazyinitialization.Application - \ No newline at end of file + diff --git a/spring-boot-properties/README.md b/spring-boot-properties/README.md new file mode 100644 index 0000000000..c43cf4865c --- /dev/null +++ b/spring-boot-properties/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Reloading Properties in Spring](https://www.baeldung.com/reloading-properties-files-in-spring/) \ No newline at end of file diff --git a/spring-boot-properties/extra.properties b/spring-boot-properties/extra.properties new file mode 100644 index 0000000000..8e28a6f889 --- /dev/null +++ b/spring-boot-properties/extra.properties @@ -0,0 +1 @@ +application.theme.color=blue \ No newline at end of file diff --git a/spring-boot-properties/extra2.properties b/spring-boot-properties/extra2.properties new file mode 100644 index 0000000000..2c46edc584 --- /dev/null +++ b/spring-boot-properties/extra2.properties @@ -0,0 +1 @@ +application.theme.background=red \ No newline at end of file diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml new file mode 100644 index 0000000000..27ac48252b --- /dev/null +++ b/spring-boot-properties/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + spring-boot-properties + jar + spring-boot-properties + Spring Boot Properties Module + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + commons-configuration + commons-configuration + ${commons-configuration.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + spring-boot-properties + + + src/main/resources + true + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + + + 1.8 + Greenwich.SR1 + 1.10 + + + diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java new file mode 100644 index 0000000000..6f76379a99 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java @@ -0,0 +1,44 @@ +package com.baeldung.properties.reloading; + +import com.baeldung.properties.reloading.configs.ReloadableProperties; +import java.io.File; +import java.util.Properties; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +@SpringBootApplication +public class SpringBootPropertiesApplication { + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public PropertiesConfiguration propertiesConfiguration( + @Value("${spring.config.location}") String path, + @Value("${spring.properties.refreshDelay}") long refreshDelay) throws Exception { + String filePath = path.substring("file:".length()); + PropertiesConfiguration configuration = new PropertiesConfiguration(new File(filePath).getCanonicalPath()); + FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy(); + fileChangedReloadingStrategy.setRefreshDelay(refreshDelay); + configuration.setReloadingStrategy(fileChangedReloadingStrategy); + return configuration; + } + + @Bean + @ConditionalOnBean(PropertiesConfiguration.class) + @Primary + public Properties properties(PropertiesConfiguration propertiesConfiguration) throws Exception { + ReloadableProperties properties = new ReloadableProperties(propertiesConfiguration); + return properties; + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootPropertiesApplication.class, args); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java new file mode 100644 index 0000000000..09c18aef33 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java @@ -0,0 +1,10 @@ +package com.baeldung.properties.reloading.configs; + +public class PropertiesException extends RuntimeException { + public PropertiesException() { + } + + public PropertiesException(Throwable cause) { + super(cause); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java new file mode 100644 index 0000000000..e90e68d09a --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java @@ -0,0 +1,49 @@ +package com.baeldung.properties.reloading.configs; + +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Properties; +import javax.naming.OperationNotSupportedException; +import org.apache.commons.configuration.PropertiesConfiguration; + +public class ReloadableProperties extends Properties { + private PropertiesConfiguration propertiesConfiguration; + + public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException { + super.load(new FileReader(propertiesConfiguration.getFile())); + this.propertiesConfiguration = propertiesConfiguration; + } + + @Override + public synchronized Object setProperty(String key, String value) { + propertiesConfiguration.setProperty(key, value); + return super.setProperty(key, value); + } + + @Override + public String getProperty(String key) { + String val = propertiesConfiguration.getString(key); + super.setProperty(key, val); + return val; + } + + @Override + public String getProperty(String key, String defaultValue) { + String val = propertiesConfiguration.getString(key, defaultValue); + super.setProperty(key, val); + return val; + } + + @Override + public synchronized void load(Reader reader) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + + @Override + public synchronized void load(InputStream inStream) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java new file mode 100644 index 0000000000..6d76a2e1e2 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java @@ -0,0 +1,33 @@ +package com.baeldung.properties.reloading.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.core.env.PropertySource; +import org.springframework.util.StringUtils; + +public class ReloadablePropertySource extends PropertySource { + + PropertiesConfiguration propertiesConfiguration; + + public ReloadablePropertySource(String name, PropertiesConfiguration propertiesConfiguration) { + super(name); + this.propertiesConfiguration = propertiesConfiguration; + } + + public ReloadablePropertySource(String name, String path) { + super(StringUtils.isEmpty(name) ? path : name); + try { + this.propertiesConfiguration = new PropertiesConfiguration(path); + FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); + strategy.setRefreshDelay(1000); + this.propertiesConfiguration.setReloadingStrategy(strategy); + } catch (Exception e) { + throw new PropertiesException(e); + } + } + + @Override + public Object getProperty(String s) { + return propertiesConfiguration.getProperty(s); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java new file mode 100644 index 0000000000..dd70e3842e --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.properties.reloading.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; + +@Configuration +public class ReloadablePropertySourceConfig { + + private ConfigurableEnvironment env; + + public ReloadablePropertySourceConfig(@Autowired ConfigurableEnvironment env) { + this.env = env; + } + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) { + ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties); + MutablePropertySources sources = env.getPropertySources(); + sources.addFirst(ret); + return ret; + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java new file mode 100644 index 0000000000..2a620b0b2d --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java @@ -0,0 +1,25 @@ +package com.baeldung.properties.reloading.configs; + +import java.io.IOException; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.FileUrlResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.DefaultPropertySourceFactory; +import org.springframework.core.io.support.EncodedResource; + +public class ReloadablePropertySourceFactory extends DefaultPropertySourceFactory { + @Override + public PropertySource createPropertySource(String s, EncodedResource encodedResource) throws IOException { + Resource internal = encodedResource.getResource(); + if (internal instanceof FileSystemResource) { + return new ReloadablePropertySource(s, ((FileSystemResource) internal).getPath()); + } + if (internal instanceof FileUrlResource) { + return new ReloadablePropertySource(s, ((FileUrlResource) internal) + .getURL() + .getPath()); + } + return super.createPropertySource(s, encodedResource); + } +} diff --git a/spring-boot-properties/src/main/resources/application.properties b/spring-boot-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..f976004a04 --- /dev/null +++ b/spring-boot-properties/src/main/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java new file mode 100644 index 0000000000..0c28cb085b --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java @@ -0,0 +1,161 @@ +package com.baeldung.properties.reloading; + +import com.baeldung.properties.reloading.beans.ConfigurationPropertiesRefreshConfigBean; +import com.baeldung.properties.reloading.beans.EnvironmentConfigBean; +import com.baeldung.properties.reloading.beans.PropertiesConfigBean; +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; +import java.io.FileOutputStream; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringBootPropertiesTestApplication.class) +public class PropertiesReloadIntegrationTest { + + protected MockMvc mvc; + + protected long refreshDelay = 3000; + + @Autowired + WebApplicationContext webApplicationContext; + + @Autowired + ValueRefreshConfigBean valueRefreshConfigBean; + + @Autowired + ConfigurationPropertiesRefreshConfigBean configurationPropertiesRefreshConfigBean; + + @Autowired + EnvironmentConfigBean environmentConfigBean; + + @Autowired + PropertiesConfigBean propertiesConfigBean; + + @Autowired + @Qualifier("singletonValueRefreshConfigBean") + ValueRefreshConfigBean singletonValueRefreshConfigBean; + + + @Before + public void setUp() throws Exception { + mvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .build(); + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + Thread.sleep(refreshDelay); + callRefresh(); + } + + @After + public void tearDown() throws Exception { + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + } + + @Test + public void givenEnvironmentReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", environmentConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", environmentConfigBean.getColor()); + } + + @Test + public void givenEnvironmentReader_whenBackgroundChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("red", environmentConfigBean.getBackgroundColor()); + + createConfig("extra2.properties", "application.theme.background", "blue"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", environmentConfigBean.getBackgroundColor()); + } + + @Test + public void givenPropertiesReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", propertiesConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", propertiesConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", valueRefreshConfigBean.getColor()); + } + + @Test + public void givenSingletonRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectOldValue() throws Exception { + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedConfigurationPropertiesReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", configurationPropertiesRefreshConfigBean.getColor()); + } + + public void callRefresh() throws Exception { + MvcResult mvcResult = mvc + .perform(MockMvcRequestBuilders + .post("/actuator/refresh") + .accept(MediaType.APPLICATION_JSON_VALUE)) + .andReturn(); + MockHttpServletResponse response = mvcResult.getResponse(); + Assert.assertEquals(response.getStatus(), 200); + } + + public void createConfig(String file, String key, String value) throws Exception { + FileOutputStream fo = new FileOutputStream(file); + fo.write(String + .format("%s=%s", key, value) + .getBytes()); + fo.close(); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java new file mode 100644 index 0000000000..50e8ef5b62 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java @@ -0,0 +1,28 @@ +package com.baeldung.properties.reloading; + +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Scope; +import org.springframework.test.context.web.WebAppConfiguration; + +@SpringBootApplication +@WebAppConfiguration +public class SpringBootPropertiesTestApplication { + + @Bean("singletonValueRefreshConfigBean") + @RefreshScope + @Scope("singleton") + public ValueRefreshConfigBean singletonValueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + + @Bean + @RefreshScope + public ValueRefreshConfigBean valueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java new file mode 100644 index 0000000000..16892b904b --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java @@ -0,0 +1,20 @@ +package com.baeldung.properties.reloading.beans; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "application.theme") +@RefreshScope +public class ConfigurationPropertiesRefreshConfigBean { + private String color; + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java new file mode 100644 index 0000000000..325e8c658e --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java @@ -0,0 +1,26 @@ +package com.baeldung.properties.reloading.beans; + +import com.baeldung.properties.reloading.configs.ReloadablePropertySourceFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "file:extra2.properties", factory = ReloadablePropertySourceFactory.class) +public class EnvironmentConfigBean { + + private Environment environment; + + public EnvironmentConfigBean(@Autowired Environment environment) { + this.environment = environment; + } + + public String getColor() { + return environment.getProperty("application.theme.color"); + } + + public String getBackgroundColor() { + return environment.getProperty("application.theme.background"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java new file mode 100644 index 0000000000..8118f6156e --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java @@ -0,0 +1,19 @@ +package com.baeldung.properties.reloading.beans; + +import java.util.Properties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PropertiesConfigBean { + + private Properties properties; + + public PropertiesConfigBean(@Autowired Properties properties) { + this.properties = properties; + } + + public String getColor() { + return properties.getProperty("application.theme.color"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java new file mode 100644 index 0000000000..1018d7c9f5 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java @@ -0,0 +1,13 @@ +package com.baeldung.properties.reloading.beans; + +public class ValueRefreshConfigBean { + private String color; + + public ValueRefreshConfigBean(String color) { + this.color = color; + } + + public String getColor() { + return color; + } +} diff --git a/spring-boot-properties/src/test/resources/application.properties b/spring-boot-properties/src/test/resources/application.properties new file mode 100644 index 0000000000..6fc241a106 --- /dev/null +++ b/spring-boot-properties/src/test/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties \ 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 435398904f..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,11 +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-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/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-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/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/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/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/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/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/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/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/README.md b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/README.md new file mode 100644 index 0000000000..81e0ffe5c8 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/README.md @@ -0,0 +1,3 @@ +## Relevant Articles: + +- [Guide to Spring Cloud Stream with Kafka, Apache Avro and Confluent Schema Registry](https://www.baeldung.com/spring-cloud-stream-kafka-avro-confluent) 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/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 9a1be3f5c0..faf27b6ac8 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -42,6 +42,18 @@ org.springframework.boot spring-boot-starter-jdbc + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java new file mode 100644 index 0000000000..318cc84957 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java @@ -0,0 +1,10 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AccountRepo extends JpaRepository{ + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java new file mode 100644 index 0000000000..8fcaa9e2aa --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java @@ -0,0 +1,27 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AccountResource { + @Autowired + private AccountRepo repo; + + @GetMapping("/account/{id}") + public ResponseEntity getAccount(@PathVariable("id") Long id) { + + Account acc = repo.findById(id).orElse(null); + if ( acc != null ) { + return new ResponseEntity(acc, HttpStatus.OK); + } + else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java new file mode 100644 index 0000000000..c4579da045 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java @@ -0,0 +1,37 @@ +/** + * + */ +package org.baeldung.spring.cloud.vaultsample; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Philippe + * + */ +@RestController +public class SecretResource { + + @Autowired + Environment env; + + @GetMapping("/secret/{key}") + public ResponseEntity readSecret(@PathVariable("key") String key) { + + String value = env.getProperty(key); + + if ( value != null ) { + return new ResponseEntity(value, HttpStatus.OK); + } + else { + return new ResponseEntity("not found", HttpStatus.NOT_FOUND); + } + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java new file mode 100644 index 0000000000..df4778831b --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java @@ -0,0 +1,133 @@ +/** + * + */ +package org.baeldung.spring.cloud.vaultsample.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +/** + * @author Philippe + * + */ +@Entity +@Table(name = "account") +public class Account { + + @Id + private Long id; + + @NotNull + private String name; + + private Long branchId; + private Long customerId; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the branchId + */ + public Long getBranchId() { + return branchId; + } + + /** + * @param branchId the branchId to set + */ + public void setBranchId(Long branchId) { + this.branchId = branchId; + } + + /** + * @return the customerId + */ + public Long getCustomerId() { + return customerId; + } + + /** + * @param customerId the customerId to set + */ + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((branchId == null) ? 0 : branchId.hashCode()); + result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Account other = (Account) obj; + if (branchId == null) { + if (other.branchId != null) + return false; + } else if (!branchId.equals(other.branchId)) + return false; + if (customerId == null) { + if (other.customerId != null) + return false; + } else if (!customerId.equals(other.customerId)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml index 3d347ec855..1c75ac21e6 100644 --- a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml @@ -1,6 +1,11 @@ -spring: - application: - name: fakebank - - datasource: - url: jdbc:mysql://localhost:3306/fakebank +spring: + application: + name: fakebank + + datasource: + url: jdbc:mysql://localhost:3306/fakebank?serverTimezone=GMT-3 + hikari: connection-test-query: select 1 + idle-timeout: 5000 + max-lifetime: 120000 + maximum-pool-size: 5 + minimum-idle: 5 diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml index 1e837c4920..7d38b06c0f 100644 --- a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml +++ b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml @@ -4,8 +4,6 @@ spring: uri: https://localhost:8200 connection-timeout: 5000 read-timeout: 15000 - config: - order: -10 ssl: trust-store: classpath:/vault.jks @@ -15,17 +13,19 @@ spring: enabled: true application-name: fakebank - kv: - enabled: false - backend: kv - application-name: fakebank - +# kv: +# enabled: false +# backend: kv +# application-name: fakebank +# database: enabled: true role: fakebank-accounts-rw -# backend: database -# username-property: spring.datasource.username -# password-property: spring.datasource.password + backend: database + username-property: spring.datasource.username + password-property: spring.datasource.password +# +# 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-vault/src/test/vault-config/vault-test.hcl b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl index c880f2d744..d16665a744 100644 --- a/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl @@ -17,4 +17,7 @@ listener "tcp" { tls_key_file = "./src/test/vault-config/localhost.key" } +// Audit to stdout + + diff --git a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt index b965a95321..2d5f2363ac 100644 --- a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt +++ b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt @@ -5,16 +5,13 @@ 2. Open another shell and execute the command below: > vault operator init -Vault will output the unseal keys and root token: STORE THEM SAFELY !!! +Unseal Key 1: Iwvpd4IVofhcmQ2HEIPs5HMUbz4tz6JhqmLZ6+1MhAPx +Unseal Key 2: ANQDXUFGGtLtt6grX25YsdmeKELhM/ioKWzwFukJIe2f +Unseal Key 3: 8MHyzFnOvlwVQzdWYJ3BIN4xPDOn8a4VemZ/Qe5HgurU +Unseal Key 4: ywT9YR9OfxIpA4l1RniNNCvSZWAuNZsAEFRyD7aqFOrp +Unseal Key 5: q1c7M+lnlT72jGLoCH+jjri6KGSBhc5lCzlT0I1R9URU -Example output: -Unseal Key 1: OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o -Unseal Key 2: iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -Unseal Key 3: K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF -Unseal Key 4: +5zhysLAO4hIdZs0kiZpkrRovw11uQacfloiBwnZBJA/ -Unseal Key 5: GDwSq18lXV3Cw4MoHsKIH137kuI0mdl36UiD9WxOdulc - -Initial Root Token: d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 +Initial Root Token: dee7107a-8819-0719-62a3-cea3ea854589 ... @@ -73,8 +70,8 @@ flush privileges; > vault write database/roles/fakebank-accounts-rw ^ db_name=mysql-fakebank ^ creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT,INSERT,UPDATE ON fakebank.* TO '{{name}}'@'%';" ^ - default_ttl="1m" ^ - max_ttl="2m" + default_ttl="5m" ^ + max_ttl="30m" === Get credentials > vault read database/creds/fakebank-accounts-rw diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.bat b/spring-cloud/spring-cloud-vault/vault-unseal.bat index 8133f90892..1e3f229fcf 100644 --- a/spring-cloud/spring-cloud-vault/vault-unseal.bat +++ b/spring-cloud/spring-cloud-vault/vault-unseal.bat @@ -1,7 +1,7 @@ call %~dp0%/vault-env.bat -vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o -vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF +vault operator unseal Iwvpd4IVofhcmQ2HEIPs5HMUbz4tz6JhqmLZ6+1MhAPx +vault operator unseal ANQDXUFGGtLtt6grX25YsdmeKELhM/ioKWzwFukJIe2f +vault operator unseal 8MHyzFnOvlwVQzdWYJ3BIN4xPDOn8a4VemZ/Qe5HgurU + 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/README.md b/spring-core-2/README.md new file mode 100644 index 0000000000..4c9e3b9ddf --- /dev/null +++ b/spring-core-2/README.md @@ -0,0 +1,3 @@ +## Relevant Articles: + +- [Understanding getBean() in Spring](https://www.baeldung.com/spring-getbean) diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index bb4ca9701b..20cd900e00 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -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-groovy/README.md b/spring-groovy/README.md index ff12555376..36404230a9 100644 --- a/spring-groovy/README.md +++ b/spring-groovy/README.md @@ -1 +1,3 @@ -## Relevant articles: +## Relevant Articles: + +- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) 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/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-security-mvc-session/src/test/resources/.gitignore b/spring-mvc-basics/.gitignore similarity index 100% rename from spring-security-mvc-session/src/test/resources/.gitignore rename to spring-mvc-basics/.gitignore 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-security-client/spring-security-jsp-config/pom.xml b/spring-mvc-basics/pom.xml similarity index 52% rename from spring-security-client/spring-security-jsp-config/pom.xml rename to spring-mvc-basics/pom.xml index 02ea206738..8c52c60b65 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -1,34 +1,27 @@ - 4.0.0 com.baeldung - spring-security-jsp-config - 0.0.1-SNAPSHOT - spring-security-jsp-config - Spring Security JSP configuration - war + spring-mvc-basics + 0.1-SNAPSHOT + spring-mvc-basics + jar - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../parent-boot-2 - - org.springframework.boot - spring-boot-starter-security - org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-tomcat - + org.apache.tomcat.embed tomcat-embed-jasper @@ -39,9 +32,23 @@ jstl - org.springframework.security - spring-security-taglibs + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-mvc-basics/src/main/java/com/baeldung/Application.java similarity index 60% rename from spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java rename to spring-mvc-basics/src/main/java/com/baeldung/Application.java index 329b104143..d58049fb35 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/Application.java @@ -1,14 +1,11 @@ -package org.baeldung.config; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application extends SpringBootServletInitializer { - +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 e5dd5ad9e1..cb16e91bc4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -144,6 +144,11 @@ spring-messaging ${spring.version}
    + + org.glassfish + javax.el + ${javax.el.version} + @@ -290,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/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-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 c978bdd983..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 @@ -129,17 +129,13 @@ 6.0.10.Final - 1.2 - 3.1.0 3.0.1-b08 19.0 - 3.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/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 index dc6a541a46..429b0c102e 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java @@ -6,4 +6,13 @@ public class Account { 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/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java deleted file mode 100644 index dc579ce4ba..0000000000 --- a/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.cors; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@EnableWebMvc -public class WebConfig implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**"); - } -} \ 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 index 07d50ae1d6..e83e13be71 100644 --- 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 @@ -2,9 +2,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.3.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc - http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> + http://www.springframework.org/schema/mvc/spring-mvc.xsd"> diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 86% rename from spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 66243ef00d..b66e642b80 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; 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/pom.xml b/spring-rest/pom.xml index 99bdd7646d..670bac9805 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -263,7 +263,6 @@ 4.0.0 1.4 3.1.0 - 3.5 20.0 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/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-security-client/README.MD b/spring-security-client/README.MD deleted file mode 100644 index 0b0af7ffe1..0000000000 --- a/spring-security-client/README.MD +++ /dev/null @@ -1,11 +0,0 @@ -========= -## Spring Security Authentication/Authorization Example Project - -##The Course -The "REST With Spring" Classes: http://github.learnspringsecurity.com - -### Relevant Articles: -- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication) - -### Build the Project -mvn clean install diff --git a/spring-security-client/pom.xml b/spring-security-client/pom.xml deleted file mode 100644 index 96ac837a09..0000000000 --- a/spring-security-client/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - 4.0.0 - spring-security-client - spring-security-client - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - spring-security-jsp-authentication - spring-security-jsp-authorize - spring-security-jsp-config - spring-security-mvc - spring-security-thymeleaf-authentication - spring-security-thymeleaf-authorize - spring-security-thymeleaf-config - - diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml deleted file mode 100644 index 9cb2a45331..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-jsp-authentication - 0.0.1-SNAPSHOT - spring-security-jsp-authentication - war - Spring Security JSP Authentication tag sample - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - javax.servlet - jstl - - - org.springframework.security - spring-security-taglibs - - - - diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java deleted file mode 100644 index c2c5939676..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index fa2a324146..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties deleted file mode 100644 index 26a80c79f3..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port: 8081 -spring.mvc.view.prefix: /WEB-INF/jsp/ -spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp deleted file mode 100644 index 90c00e980a..0000000000 --- a/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp +++ /dev/null @@ -1,24 +0,0 @@ - <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - -Spring Security JSP Authorize - - - - - -
    - Current user name: -
    - Current user roles: -
    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml deleted file mode 100644 index ad4c9d105b..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-jsp-authorize - 0.0.1-SNAPSHOT - spring-security-jsp-authorize - Spring Security JSP Authorize tag sample - war - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - javax.servlet - jstl - - - org.springframework.security - spring-security-taglibs - - - - diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java deleted file mode 100644 index c2c5939676..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index fa2a324146..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties deleted file mode 100644 index 26a80c79f3..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port: 8081 -spring.mvc.view.prefix: /WEB-INF/jsp/ -spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp deleted file mode 100644 index 08af845bd4..0000000000 --- a/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp +++ /dev/null @@ -1,33 +0,0 @@ - <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - -Spring Security JSP Authorize - - - - - -
    - - Only admins can see this message - - - - Only users can see this message - -
    - - - Only users who can call "/admin" URL can see this message - -
    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java deleted file mode 100644 index c2c5939676..0000000000 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index fa2a324146..0000000000 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties deleted file mode 100644 index 26a80c79f3..0000000000 --- a/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port: 8081 -spring.mvc.view.prefix: /WEB-INF/jsp/ -spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp deleted file mode 100644 index bd5ccb0c78..0000000000 --- a/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp +++ /dev/null @@ -1,21 +0,0 @@ - - - - -Spring Security JSP - - - - - -
    - Welcome -
    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml deleted file mode 100644 index 75298026a8..0000000000 --- a/spring-security-client/spring-security-mvc/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-mvc - 0.0.1-SNAPSHOT - spring-security-mvc - Spring Security MVC - war - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - - diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java deleted file mode 100644 index 34c43fbe5a..0000000000 --- a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/src/main/resources/application.properties b/spring-security-client/spring-security-mvc/src/main/resources/application.properties deleted file mode 100644 index c2eee0d931..0000000000 --- a/spring-security-client/spring-security-mvc/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port: 8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/src/main/resources/logback.xml b/spring-security-client/spring-security-mvc/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-client/spring-security-mvc/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 66243ef00d..0000000000 --- a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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 SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml deleted file mode 100644 index 01d2c6bdbe..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - com.baeldung - spring-security-thymeleaf-authentication - 0.0.1-SNAPSHOT - spring-security-thymeleaf-authentication - Spring Security thymeleaf authentication tag sample - war - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity4 - - - - diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index 259433f6ae..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.context.annotation.Profile; - -@Configuration -@EnableWebMvc -@Profile("!manual") -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java deleted file mode 100644 index d80527c30a..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfigManual.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@Profile("manual") -public class MvcConfigManual extends WebMvcConfigurerAdapter { - - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/home").setViewName("home"); - registry.addViewController("/").setViewName("home"); - registry.addViewController("/hello").setViewName("hello"); - registry.addViewController("/login").setViewName("login"); - } - -} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java deleted file mode 100644 index 2414ff9cac..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/RegistrationController.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.config; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.WebAuthenticationDetails; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration) - * (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc) - * - * @author jim clayson - */ -@Controller -@Profile("manual") -public class RegistrationController { - private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class); - - @Autowired - private AuthenticationManager authenticationManager; - - /** - * For demo purposes this need only be a GET request method - * - * @param request - * @param response - * @return The view. Page confirming either successful registration (and/or - * successful authentication) or failed registration. - */ - @GetMapping("/register") - public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) { - logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate."); - - // Mocked values. Potentially could come from an HTML registration form, - // in which case this mapping would match on an HTTP POST, rather than a GET - String username = "user"; - String password = "password"; - - if (requestQualifiesForManualAuthentication()) { - try { - authenticate(username, password, request, response); - logger.debug("registerAndAuthenticate: authentication completed."); - } catch (BadCredentialsException bce) { - logger.debug("Authentication failure: bad credentials"); - bce.printStackTrace(); - return "systemError"; // assume a low-level error, since the registration - // form would have been successfully validated - } - } - - return "registrationSuccess"; - } - - private boolean requestQualifiesForManualAuthentication() { - // Some processing to determine that the user requires a Spring Security-recognized, - // application-directed login e.g. successful account registration. - return true; - } - - private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException { - logger.debug("attempting to authenticated, manually ... "); - - // create and populate the token - AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password); - authToken.setDetails(new WebAuthenticationDetails(request)); - - // This call returns an authentication object, which holds principle and user credentials - Authentication authentication = this.authenticationManager.authenticate(authToken); - - // The security context holds the authentication object, and is stored - // in thread local scope. - SecurityContextHolder.getContext().setAuthentication(authentication); - - logger.debug("User should now be authenticated."); - } - -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index 153cc67661..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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.context.annotation.Profile; - -@Configuration -@EnableWebSecurity -@Profile("!manual") -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java deleted file mode 100644 index 180a53deba..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/WebSecurityConfigManual.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -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; - -@Configuration -@EnableWebSecurity -@Profile("manual") -public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http - .authorizeRequests() - .antMatchers("/", "/home", "/register").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/login").permitAll() - .and() - .logout().permitAll(); - // @formatter:on - } - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); - } -} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties deleted file mode 100644 index bafddced85..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html deleted file mode 100644 index b37731b0ed..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/hello.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - Hello World! - - -

    Hello [[${#httpServletRequest.remoteUser}]]!

    -
    - -
    -

    Click here to go to the home page.

    - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html deleted file mode 100644 index 6dbdf491c6..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/home.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - Spring Security Example - - -

    Welcome!

    - -

    Click here to see a greeting.

    -

    Click here to send a dummy registration request, where the application logs you in.

    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html deleted file mode 100644 index c65b5f092b..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - -Spring Security Thymeleaf - - - - - -
    - Current user name: Bob -
    - Current user roles: [ROLE_USER, ROLE_ADMIN] -
    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html deleted file mode 100644 index 3f28efac69..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/login.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - Spring Security Example - - -
    - Invalid username and password. -
    -
    - You have been logged out. -
    -
    -
    -
    -
    -
    -

    Click here to go to the home page.

    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html deleted file mode 100644 index 756cc2390d..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationError.html +++ /dev/null @@ -1 +0,0 @@ -Registration could not be completed at this time. Please try again later or contact support! \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html deleted file mode 100644 index b1c4336f2f..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/registrationSuccess.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - Registration Success! - - -

    Registration succeeded. You have been logged in by the system. Welcome [[${#httpServletRequest.remoteUser}]]!

    -
    - -
    -

    Click here to go to the home page.

    - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 66243ef00d..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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 SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml deleted file mode 100644 index 8c600c1f81..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - com.baeldung - spring-security-thymeleaf-authorize - 0.0.1-SNAPSHOT - spring-security-thymeleaf-authorize - Spring Security thymeleaf authorize tag sample - war - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity4 - - - - diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index 9ade60e54c..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties deleted file mode 100644 index bafddced85..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html deleted file mode 100644 index fcbbfb4957..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - -Spring Security Thymeleaf - - - - - -
    -
    - Only admins can see this message -
    - -
    - Only users can see this message -
    -
    - -
    - Only users who can call "/admin" URL can see this message -
    -
    - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 66243ef00d..0000000000 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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 SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml deleted file mode 100644 index aeda999405..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-thymeleaf-config - 0.0.1-SNAPSHOT - spring-security-thymeleaf-config - Spring Security thymeleaf configuration sample project - war - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity4 - - - - diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java deleted file mode 100644 index 9ade60e54c..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - // - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java deleted file mode 100644 index bd6c56d38a..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -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; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("john").password("123").roles("USER") - .and() - .withUser("tom").password("111").roles("ADMIN"); - // @formatter:on - } - - @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() - ; - // @formatter:on - } -} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties deleted file mode 100644 index bafddced85..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 66243ef00d..0000000000 --- a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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 SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-core/README.md b/spring-security-core/README.md index b38dc061b4..bc9a8afed7 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -10,3 +10,4 @@ mvn clean install - [Spring Security – @PreFilter and @PostFilter](http://www.baeldung.com/spring-security-prefilter-postfilter) - [Spring Boot Authentication Auditing Support](http://www.baeldung.com/spring-boot-authentication-audit) - [Introduction to Spring Method Security](http://www.baeldung.com/spring-security-method-security) +- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) \ No newline at end of file diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 37d8c34c5a..db0c9135c4 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -1,11 +1,15 @@ package org.baeldung.app; +import javax.servlet.Filter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication @EnableJpaRepositories("org.baeldung.repository") @@ -15,4 +19,32 @@ public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } + + public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected javax.servlet.Filter[] getServletFilters() { + DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); + delegateFilterProxy.setTargetBeanName("loggingFilter"); + return new Filter[] { delegateFilterProxy }; + } + + @Override + protected Class[] getRootConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected String[] getServletMappings() { + // TODO Auto-generated method stub + return null; + } + } } diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java similarity index 96% rename from spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java rename to spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java index 4aa33cd749..35596eae16 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java +++ b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.filter; +package org.baeldung.filter; import java.io.IOException; diff --git a/spring-security-core/src/main/webapp/WEB-INF/web.xml b/spring-security-core/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e4954338a9 --- /dev/null +++ b/spring-security-core/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + + loggingFilter + org.springframework.web.filter.DelegatingFilterProxy + + + + loggingFilter + /* + + + \ No newline at end of file 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-cors/README.md b/spring-security-cors/README.md new file mode 100644 index 0000000000..2ab5e33ee3 --- /dev/null +++ b/spring-security-cors/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 4c25dc01e8..906bebf442 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -1,12 +1,13 @@ - + 4.0.0 com.baeldung spring-security-mvc-boot 0.0.1-SNAPSHOT spring-security-mvc-boot - war + pom Spring Security MVC Boot @@ -45,10 +46,6 @@ org.springframework.security spring-security-data - - com.h2database - h2 - org.hamcrest hamcrest-core @@ -198,7 +195,7 @@ **/*LiveTest.java **/*IntegrationTest.java - **/*IntTest.java + **/*IntTest.java **/*EntryPointsTest.java @@ -217,22 +214,13 @@ + + spring-security-mvc-boot-default + spring-security-mvc-boot-mysql + spring-security-mvc-boot-postgre + - org.baeldung.custom.Application - - - - - - - - - 1.1.2 1.6.1 2.6.11 diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml new file mode 100644 index 0000000000..8f7f18f093 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-default + 0.0.1-SNAPSHOT + spring-security-mvc-boot-default + jar + Spring Security MVC Boot + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + ../ + + + + + com.h2database + h2 + + + + + org.baeldung.custom.Application + + + + + + + + + + + diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java similarity index 74% rename from spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java index 329b104143..682d429963 100644 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java @@ -1,14 +1,12 @@ -package org.baeldung.config; +package org.baeldung.custom; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } - } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java new file mode 100644 index 0000000000..6bd30414ef --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -0,0 +1,15 @@ +package org.baeldung.jdbcauthentication.h2; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableWebSecurity +public class H2JdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(H2JdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java new file mode 100644 index 0000000000..8b8696f0b2 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -0,0 +1,51 @@ +package org.baeldung.jdbcauthentication.h2.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll(); + httpSecurity.csrf() + .ignoringAntMatchers("/h2-console/**"); + httpSecurity.headers() + .frameOptions() + .sameOrigin(); + } + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .withDefaultSchema() + .withUser(User.withUsername("user") + .password(passwordEncoder().encode("pass")) + .roles("USER")); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java new file mode 100644 index 0000000000..0955061614 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java @@ -0,0 +1,17 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 69% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java index e9dc541ad3..d25324eb54 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,11 +1,8 @@ package org.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("org.baeldung.multiplelogin") diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/resources/application-ssl.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/application-ssl.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties similarity index 74% rename from spring-security-mvc-boot/src/main/resources/application.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties index 25eac743d1..365dedab9e 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties @@ -8,5 +8,7 @@ spring.jpa.database=H2 spring.jpa.show-sql=false spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +logging.level.org.springframework.security.web.FilterChainProxy=DEBUG -#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG \ No newline at end of file +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 similarity index 100% rename from spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 diff --git a/rest-with-spark-java/src/main/resources/logback.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml similarity index 100% rename from rest-with-spark-java/src/main/resources/logback.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml diff --git a/spring-security-mvc-boot/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/persistence-h2.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-ip.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml diff --git a/spring-security-mvc-boot/src/main/resources/templates/403.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/403.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/adminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/adminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html similarity index 100% rename from spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginUser.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginUser.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/private.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/userPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/userPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..638e9d7919 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.authentication.FormAuthConfig; +import io.restassured.filter.session.SessionFilter; + +/** + * This Live Test requires the H2JdbcAuthenticationApplication application to be up and running + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + SessionFilter filter = new SessionFilter(); + given().auth() + .form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf")) + .and() + .filter(filter) + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml new file mode 100644 index 0000000000..765953c557 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-mysql + 0.0.1-SNAPSHOT + spring-security-mvc-boot-mysql + jar + Spring Security MVC Boot using MySQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + mysql + mysql-connector-java + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..238a48730c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.mysql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MySqlJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(MySqlJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java new file mode 100644 index 0000000000..a0584818cd --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select email,password,enabled " + + "from bael_users " + + "where email = ?") + .authoritiesByUsernameQuery("select email,authority " + + "from authorities " + + "where email = ?"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java new file mode 100644 index 0000000000..ed15f8bfe6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties new file mode 100644 index 0000000000..2962475108 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication +spring.datasource.username=root +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql new file mode 100644 index 0000000000..8214fd8204 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user@email.com/pass +INSERT INTO bael_users (name, email, password, enabled) values ('user', 'user@email.com', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', 1); + +INSERT INTO authorities (email, authority) values ('user@email.com', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql new file mode 100644 index 0000000000..bb38c74366 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql @@ -0,0 +1,18 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS bael_users; + +CREATE TABLE bael_users ( + name VARCHAR(50) NOT NULL, + email VARCHAR(50) NOT NULL, + password VARCHAR(100) NOT NULL, + enabled TINYINT NOT NULL DEFAULT 1, + PRIMARY KEY (email) +); + +CREATE TABLE authorities ( + email VARCHAR(50) NOT NULL, + authority VARCHAR(50) NOT NULL, + FOREIGN KEY (email) REFERENCES bael_users(email) +); + +CREATE UNIQUE INDEX ix_auth_email on authorities (email,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2c19e2c0ca --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.jdbcauthentication.mysql; + +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 = MySqlJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..79bc84ea69 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user@email.com", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user@email.com")) + .body("name", is("user@email.com")); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml new file mode 100644 index 0000000000..e68e47b596 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-postgre + 0.0.1-SNAPSHOT + spring-security-mvc-boot-postgre + jar + Spring Security MVC Boot using PostgreSQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + org.postgresql + postgresql + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..d4b555e8c6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.postgre; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PostgreJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(PostgreJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java new file mode 100644 index 0000000000..85dc9d364c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.jdbcauthentication.postgre.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java new file mode 100644 index 0000000000..da85a46562 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties new file mode 100644 index 0000000000..2940c5121e --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication +spring.datasource.username=postgres +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql new file mode 100644 index 0000000000..fcc6b54949 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user/pass +INSERT INTO users (username, password, enabled) values ('user', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', true); + +INSERT INTO authorities (username, authority) values ('user', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql new file mode 100644 index 0000000000..d78edfb528 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql @@ -0,0 +1,16 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS users; + +CREATE TABLE users ( + username varchar(50) NOT NULL PRIMARY KEY, + password varchar(100) NOT NULL, + enabled boolean not null DEFAULT true +); + +CREATE TABLE authorities ( + username varchar(50) NOT NULL, + authority varchar(50) NOT NULL, + CONSTRAINT foreign_authorities_users_1 foreign key(username) references users(username) +); + +CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f133ef73be --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre; + +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.jdbcauthentication.postgre.PostgreJdbcAuthenticationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PostgreJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..b5f4379c0a --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java deleted file mode 100644 index f932ac3066..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.custom; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-security-mvc-boot/src/main/resources/logback.xml b/spring-security-mvc-boot/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-mvc-boot/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/templates/index.html b/spring-security-mvc-boot/src/main/resources/templates/index.html deleted file mode 100644 index 8e7394ad6a..0000000000 --- a/spring-security-mvc-boot/src/main/resources/templates/index.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - -Spring Security Thymeleaf - - - - - -
    - Welcome -
    - - \ No newline at end of file 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-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-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java similarity index 93% rename from spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java index 9e74e83a53..5ee80d856a 100644 --- a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java @@ -11,7 +11,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) @WebAppConfiguration -public class SpringContextIntegrationTest { +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 deleted file mode 100644 index 276f651436..0000000000 --- a/spring-security-mvc-session/pom.xml +++ /dev/null @@ -1,126 +0,0 @@ - - 4.0.0 - com.baeldung - spring-security-mvc-session - 0.1-SNAPSHOT - spring-security-mvc-session - war - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-taglibs - - - - - org.springframework.boot - spring-boot-starter-web - - - org.apache.tomcat.embed - tomcat-embed-jasper - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - javax.servlet - javax.servlet-api - provided - - - - javax.servlet - jstl - runtime - - - - - - com.codahale.metrics - metrics-core - ${codahale.metrics.version} - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - spring-security-mvc-session - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - - - - - - - 3.0.2 - - - 2.6 - 1.6.1 - - - \ No newline at end of file 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 deleted file mode 100644 index b9f50ded73..0000000000 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -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; - -@EnableWebMvc -@Configuration -public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - - registry.addViewController("/anonymous.html"); - - registry.addViewController("/login.html"); - registry.addViewController("/homepage.html"); - registry.addViewController("/sessionExpired.html"); - registry.addViewController("/invalidExpired.html"); - registry.addViewController("/console.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} \ No newline at end of file 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-mvc/.gitignore b/spring-security-mvc/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-security-mvc/.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-security-mvc-session/README.md b/spring-security-mvc/README.md similarity index 100% rename from spring-security-mvc-session/README.md rename to spring-security-mvc/README.md diff --git a/spring-security-mvc/pom.xml b/spring-security-mvc/pom.xml new file mode 100644 index 0000000000..98ad3daa46 --- /dev/null +++ b/spring-security-mvc/pom.xml @@ -0,0 +1,84 @@ + + 4.0.0 + com.baeldung + spring-security-mvc + 0.1-SNAPSHOT + spring-security-mvc + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-taglibs + + + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + org.springframework.boot + spring-boot-starter-tomcat + + + + javax.servlet + jstl + runtime + + + + + io.dropwizard.metrics + metrics-core + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.SpringSessionApplication + JAR + + + + + + diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java similarity index 93% rename from spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java rename to spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java index 9e52f0430a..c2a4b35df0 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java +++ b/spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java similarity index 95% rename from spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java rename to spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java index ed253305ed..e2224996c2 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java +++ b/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java @@ -1,4 +1,4 @@ -package org.baeldung.monitoring; +package com.baeldung.monitoring; import java.util.concurrent.TimeUnit; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 99% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f49ea59d..9d4fc19098 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Collection; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java b/spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java similarity index 97% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java rename to spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java index d37d46e478..f4f876af9c 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java +++ b/spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Arrays; diff --git a/spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..38a4f3f81b --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class MvcConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/anonymous.html"); + + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/sessionExpired.html"); + registry.addViewController("/invalidSession.html"); + registry.addViewController("/console.html"); + } + + + /* + * Spring Boot supports configuring a ViewResolver with properties + */ +// @Bean +// public ViewResolver viewResolver() { +// final InternalResourceViewResolver bean = new InternalResourceViewResolver(); +// +// bean.setViewClass(JstlView.class); +// bean.setPrefix("/WEB-INF/view/"); +// bean.setSuffix(".jsp"); +// } +} diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 91% rename from spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java index b7996ebf18..a922ba6f7f 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,11 +1,9 @@ -package org.baeldung.spring; +package com.baeldung.spring; -import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -13,9 +11,10 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; +import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; + @Configuration // @ImportResource({ "classpath:webSecurityConfig.xml" }) -@EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { @@ -39,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .csrf().disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() + .antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll() .anyRequest().authenticated() .and() .formLogin() @@ -70,7 +69,7 @@ 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/java/org/baeldung/web/SessionListenerWithMetrics.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java similarity index 92% rename from spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java rename to spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java index 46bf2708f7..fb1a81744e 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java +++ b/spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java @@ -1,12 +1,11 @@ -package org.baeldung.web; +package com.baeldung.web; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; -import org.baeldung.monitoring.MetricRegistrySingleton; - +import com.baeldung.monitoring.MetricRegistrySingleton; import com.codahale.metrics.Counter; public class SessionListenerWithMetrics implements HttpSessionListener { diff --git a/spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java new file mode 100644 index 0000000000..1353ee25d0 --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java @@ -0,0 +1,17 @@ +package com.baeldung.web; + +import javax.servlet.http.HttpSession; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SessionRestController { + + @GetMapping("/session-max-interval") + @ResponseBody + public String retrieveMaxSessionIncativeInterval(HttpSession session) { + return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval(); + } +} diff --git a/spring-security-mvc/src/main/resources/application.properties b/spring-security-mvc/src/main/resources/application.properties new file mode 100644 index 0000000000..56b2b7b123 --- /dev/null +++ b/spring-security-mvc/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.servlet.session.timeout=65s + +spring.mvc.view.prefix=/WEB-INF/view/ +spring.mvc.view.suffix=.jsp + +## Secure Session Cookie configurations +#server.servlet.session.cookie.http-only=true +#server.servlet.session.cookie.secure=true \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/resources/logback.xml b/spring-security-mvc/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/logback.xml rename to spring-security-mvc/src/main/resources/logback.xml diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc/src/main/resources/webSecurityConfig.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/webSecurityConfig.xml rename to spring-security-mvc/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/web.xml diff --git a/spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8e53a6371a --- /dev/null +++ b/spring-security-mvc/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 +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java new file mode 100644 index 0000000000..7d9a03d5f6 --- /dev/null +++ b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java @@ -0,0 +1,92 @@ +package com.baeldung.session; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.junit.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.filter.session.SessionFilter; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +/** + * This Live Test requires the service to be up and running. + */ +public class SessionConfigurationLiveTest { + + private static final String USER = "user1"; + private static final String PASSWORD = "user1Pass"; + private static final String SESSION_SVC_URL = "http://localhost:8080/session-max-interval"; + + @Test + public void givenValidUser_whenRequestResourceAfterSessionExpiration_thenRedirectedToInvalidSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + Response resp2 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + assertThat(resp2.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(resp2.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + + // session will be expired in 60 seconds... + Thread.sleep(62000); + Response resp3 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + + assertThat(resp3.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp3.getHeader("Location")).isEqualTo("http://localhost:8080/invalidSession.html"); + } + + @Test + public void givenValidUser_whenLoginMoreThanMaxValidSession_thenRedirectedToExpiredSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + simpleSvcRequestLoggingIn(); + + // this login will expire the first session + simpleSvcRequestLoggingIn(); + + // now try to access a resource using expired session + Response resp4 = given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + + assertThat(resp4.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp4.getHeader("Location")).isEqualTo("http://localhost:8080/sessionExpired.html"); + } + + private static void simpleSvcRequestLoggingIn() { + simpleSvcRequestLoggingIn(null); + } + + private static void simpleSvcRequestLoggingIn(SessionFilter sessionFilter) { + Response response = simpleResponseSvcRequestLoggingIn(Optional.ofNullable(sessionFilter)); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(response.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + } + + private static Response simpleResponseSvcRequestLoggingIn(Optional sessionFilter) { + RequestSpecification spec = given().auth() + .form(USER, PASSWORD); + sessionFilter.ifPresent(filter -> spec.and() + .filter(filter)); + return spec.when() + .get(SESSION_SVC_URL); + } + + private static Response simpleResponseRequestUsingSessionNotFollowingRedirects(SessionFilter sessionFilter) { + return given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + } + +} diff --git a/spring-security-mvc/src/test/resources/.gitignore b/spring-security-mvc/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-security-mvc/src/test/resources/.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-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/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/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 16f19b681f..e155a0f6b2 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -62,7 +62,6 @@ - 1.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/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/README.md b/spring-thymeleaf-2/README.md new file mode 100644 index 0000000000..9bd441a6bd --- /dev/null +++ b/spring-thymeleaf-2/README.md @@ -0,0 +1,3 @@ +## Relevant Articles: + +- [Working with Enums in Thymeleaf](https://www.baeldung.com/thymeleaf-enums) 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/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java new file mode 100644 index 0000000000..eebe37e000 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java @@ -0,0 +1,28 @@ +package com.example.demo; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; + +import static java.util.Arrays.asList; + +@Controller +public class ParticipantController { + + @RequestMapping("/") + public String index( + @RequestParam(value = "participant", required = false) String participant, + @RequestParam(value = "country", required = false) String country, + @RequestParam(value = "action", required = false) String action, + @RequestParam(value = "id", required = false) Integer id, + Model model + ) { + model.addAttribute("id", id); + List userIds = asList(1,2,3,4); + model.addAttribute("userIds", userIds); + return "participants"; + } +} diff --git a/spring-thymeleaf/src/main/resources/templates/participants.html b/spring-thymeleaf/src/main/resources/templates/participants.html new file mode 100644 index 0000000000..8d4e552093 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/templates/participants.html @@ -0,0 +1,32 @@ + + + + + +

    Enter participant

    +
    + + + + + +
    + + +

    User Details

    +

    Details for user [[${id}]] ...

    +
    + +

    Users

    + +

    + User [[${userId}]] +

    +
    + + 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/.gitignore b/spring-userservice/.gitignore deleted file mode 100644 index afe61e7c0c..0000000000 --- a/spring-userservice/.gitignore +++ /dev/null @@ -1 +0,0 @@ -derby.log \ No newline at end of file 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/logback.xml b/spring-userservice/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-userservice/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file 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/SpringContextIntegrationTest.java deleted file mode 100644 index 825b89eb10..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -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 = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -public class SpringContextIntegrationTest { - - @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/testing-modules/easy-random/README.md b/testing-modules/easy-random/README.md new file mode 100644 index 0000000000..117d636bcc --- /dev/null +++ b/testing-modules/easy-random/README.md @@ -0,0 +1,3 @@ +## Relevant Articles: + +- [Quick Guide to EasyRandom in Java](https://www.baeldung.com/java-easy-random) diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md new file mode 100644 index 0000000000..61a65b2e5a --- /dev/null +++ b/testing-modules/junit-5-advanced/README.md @@ -0,0 +1,4 @@ +## Relevant Articles: + +- [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher) +- [JUnit Custom Display Name Generator API](https://www.baeldung.com/junit-custom-display-name-generator) 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/spring-security-client/spring-security-jsp-authentication/src/main/resources/logback.xml b/testing-modules/junit-5-advanced/src/main/resources/logback.xml similarity index 100% rename from spring-security-client/spring-security-jsp-authentication/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/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 c09c030780..dbe6803401 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,5 +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-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-basics/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/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-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..6833834959 --- /dev/null +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,39 @@ +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; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void whenDivideByValidNumber_thenAssertCorrectResult() { + 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 whenDivideNumbers_thenExpectWrongResult() { + 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 whenDivideByZero_thenThrowsException() { + SimpleCalculator.divideNumbers(10, 0); + } + + @Test + void whenDivideByZero_thenAssertException(){ + assertThrows(ArithmeticException.class, () -> SimpleCalculator.divideNumbers(10, 0)); + } + +} 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/README.md b/testing-modules/load-testing-comparison/README.md new file mode 100644 index 0000000000..9823be5369 --- /dev/null +++ b/testing-modules/load-testing-comparison/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) 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 19dbaa0dc1..7b6d6e7735 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -94,7 +94,6 @@ 2.0.9.RELEASE 19.0 - 3.5 1.7.0 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/parallel-tests-junit/README.md b/testing-modules/parallel-tests-junit/README.md new file mode 100644 index 0000000000..0b7834c5e7 --- /dev/null +++ b/testing-modules/parallel-tests-junit/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 3a1c3f3bf4..8d40c668c0 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -36,5 +36,6 @@ 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 0970eabeff..1b06c13953 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -1,8 +1,8 @@ -### Relevant Articles: +## Relevant Articles: - [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) - [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) - [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) -- [Override properties in Spring]() +- [Override Properties in Spring’s Tests](https://www.baeldung.com/spring-tests-override-properties) diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index f4d7b5dc66..6f2700e2df 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -73,7 +73,7 @@ javax.servlet javax.servlet-api - ${servlet.api.version} + ${javax.servlet-api.version} @@ -94,7 +94,7 @@ 3.1.6 5.4.0 5.1.4.RELEASE - 4.0.1 + 4.0.1 2.1.1 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 9e146ccf33..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 + ../../ 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/spring-security-client/spring-security-jsp-authorize/src/main/resources/logback.xml b/testing-modules/xmlunit-2/src/main/resources/logback.xml similarity index 100% rename from spring-security-client/spring-security-jsp-authorize/src/main/resources/logback.xml rename to testing-modules/xmlunit-2/src/main/resources/logback.xml 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/Twitter4J/README.md b/twitter4j/README.md similarity index 100% rename from Twitter4J/README.md rename to twitter4j/README.md diff --git a/Twitter4J/pom.xml b/twitter4j/pom.xml similarity index 100% rename from Twitter4J/pom.xml rename to twitter4j/pom.xml diff --git a/Twitter4J/src/main/java/com/baeldung/Application.java b/twitter4j/src/main/java/com/baeldung/Application.java similarity index 100% rename from Twitter4J/src/main/java/com/baeldung/Application.java rename to twitter4j/src/main/java/com/baeldung/Application.java diff --git a/spring-security-client/spring-security-jsp-config/src/main/resources/logback.xml b/twitter4j/src/main/resources/logback.xml similarity index 100% rename from spring-security-client/spring-security-jsp-config/src/main/resources/logback.xml rename to twitter4j/src/main/resources/logback.xml diff --git a/Twitter4J/src/main/resources/twitter4j.properties b/twitter4j/src/main/resources/twitter4j.properties similarity index 100% rename from Twitter4J/src/main/resources/twitter4j.properties rename to twitter4j/src/main/resources/twitter4j.properties diff --git a/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/twitter4j/src/test/java/com/baeldung/ApplicationLiveTest.java similarity index 95% rename from Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java rename to twitter4j/src/test/java/com/baeldung/ApplicationLiveTest.java index 4696283faa..0d4114e72d 100644 --- a/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java +++ b/twitter4j/src/test/java/com/baeldung/ApplicationLiveTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import twitter4j.TwitterException; -public class ApplicationIntegrationTest { +public class ApplicationLiveTest { /** * In order run this jUnit test you need to configure your API details in the twitter4j.properties 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/vaadin/src/main/java/com/baeldung/introduction/Row.java b/vaadin/src/main/java/com/baeldung/introduction/Row.java new file mode 100644 index 0000000000..412a286376 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/Row.java @@ -0,0 +1,45 @@ +package com.baeldung.introduction; + +public class Row { + + private String column1; + + private String column2; + + private String column3; + + public Row() { + + } + + public Row(String column1, String column2, String column3) { + super(); + this.column1 = column1; + this.column2 = column2; + this.column3 = column3; + } + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public String getColumn2() { + return column2; + } + + public void setColumn2(String column2) { + this.column2 = column2; + } + + public String getColumn3() { + return column3; + } + + public void setColumn3(String column3) { + this.column3 = column3; + } +} \ No newline at end of file diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 68be53b1b3..22ce19f5e0 100644 --- a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -201,10 +201,14 @@ public class VaadinUI extends UI { TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); twinColSelect.setItems(numbers); - Grid grid = new Grid("Grid"); - grid.setColumns("Column1", "Column2", "Column3"); - grid.setItems("Item1", "Item2", "Item3"); - grid.setItems("Item4", "Item5", "Item6"); + Grid grid = new Grid(Row.class); + grid.setColumns("column1", "column2", "column3"); + Row row1 = new Row("Item1", "Item2", "Item3"); + Row row2 = new Row("Item4", "Item5", "Item6"); + List rows = new ArrayList(); + rows.add(row1); + rows.add(row2); + grid.setItems(rows); Panel panel = new Panel("Panel"); panel.setContent(grid); @@ -271,7 +275,7 @@ public class VaadinUI extends UI { setContent(verticalLayout); } - @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @WebServlet(urlPatterns = "/VAADIN/*", name = "MyUIServlet", asyncSupported = true) @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } diff --git a/video-tutorials/README.md b/video-tutorials/README.md index ff12555376..729105e3fd 100644 --- a/video-tutorials/README.md +++ b/video-tutorials/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: 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 e9b89c71fc..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,18 +24,31 @@ jaxen ${jaxen.version} - + + org.jooq + joox-java-6 + ${joox.version} + org.jdom jdom2 ${jdom2.version} - - javax.xml + javax.xml.bind jaxb-api ${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 @@ -45,7 +59,17 @@ stax-api ${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,16 +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.1 + 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 @@ -263,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/xmlunit-2/src/main/resources/logback.xml b/xmlunit-2/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/xmlunit-2/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/xstream/README.md b/xstream/README.md index e8302c14ef..bf917e81fb 100644 --- a/xstream/README.md +++ b/xstream/README.md @@ -1,4 +1,6 @@ -### Relevant Articles: +## Relevant Articles: + - [XStream User Guide: JSON](http://www.baeldung.com/xstream-json-processing) - [XStream User Guide: Converting XML to Objects](http://www.baeldung.com/xstream-deserialize-xml-to-object) - [XStream User Guide: Converting Objects to XML](http://www.baeldung.com/xstream-serialize-object-to-xml) +- [Remote Code Execution with XStream](https://www.baeldung.com/java-xstream-remote-code-execution)