From 334137939be5d9a9757729bf8a953a68662535b3 Mon Sep 17 00:00:00 2001 From: Simon <7910919+smic1909@users.noreply.github.com> Date: Thu, 6 Sep 2018 11:45:25 +0200 Subject: [PATCH 01/39] Fixed assignment of restTemplate Fixed assignment of restTemplate --- .../main/java/org/baeldung/web/service/BarConsumerService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java b/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java index 4188677b4f..0bf24bd480 100644 --- a/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java +++ b/spring-resttemplate/src/main/java/org/baeldung/web/service/BarConsumerService.java @@ -14,7 +14,7 @@ public class BarConsumerService { @Autowired public BarConsumerService(RestTemplateBuilder restTemplateBuilder) { - RestTemplate restTemplate = restTemplateBuilder + restTemplate = restTemplateBuilder .errorHandler(new RestTemplateResponseErrorHandler()) .build(); } From 51a583b229141c1618279bed7653fdd61bf06c38 Mon Sep 17 00:00:00 2001 From: cror Date: Thu, 6 Sep 2018 22:25:49 +0200 Subject: [PATCH 02/39] spring-5-reactive-security: fixing EmployeeControllerIntegrationTest --- .../reactive/webflux/EmployeeControllerIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java index 3dc832d781..12a21ed4ef 100644 --- a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/webflux/EmployeeControllerIntegrationTest.java @@ -15,7 +15,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -import com.baeldung.reactive.actuator.Spring5ReactiveApplication; +import com.baeldung.webflux.EmployeeSpringApplication; import com.baeldung.webflux.Employee; import com.baeldung.webflux.EmployeeRepository; @@ -23,7 +23,7 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=Spring5ReactiveApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes=EmployeeSpringApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmployeeControllerIntegrationTest { From 33d5e710845a943b08ebb6b4aada6c6bf7378d82 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sun, 23 Sep 2018 15:26:48 +0200 Subject: [PATCH 03/39] added link --- java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-strings/README.md b/java-strings/README.md index 233d986d98..1286f7b6c9 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -27,3 +27,4 @@ - [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) +- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) From 8ca0e9a84711edfd712bced5b6cf659a53dd783a Mon Sep 17 00:00:00 2001 From: dupirefr Date: Mon, 1 Oct 2018 19:30:04 +0200 Subject: [PATCH 04/39] [BAEL-2183] Arrays manipulations --- .../baeldung/array/ArrayReferenceGuide.java | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java diff --git a/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java b/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java new file mode 100644 index 0000000000..7d7dec85b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java @@ -0,0 +1,159 @@ +package com.baeldung.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class ArrayReferenceGuide { + + public static void main(String[] args) { + declaration(); + + initialization(); + + access(); + + iterating(); + + varargs(); + + transformIntoList(); + + transformIntoStream(); + + sort(); + + search(); + + merge(); + } + + private static void declaration() { + int[] anArray; + int anotherArray[]; + } + + private static void initialization() { + int[] anArray = new int[10]; + anArray[0] = 10; + anArray[5] = 4; + + int[] anotherArray = new int[] {1, 2, 3, 4, 5}; + } + + private static void access() { + int[] anArray = new int[10]; + anArray[0] = 10; + anArray[5] = 4; + + System.out.println(anArray[0]); + } + + private static void iterating() { + int[] anArray = new int[] {1, 2, 3, 4, 5}; + for (int i = 0; i < anArray.length; i++) { + System.out.println(anArray[i]); + } + + for (int element : anArray) { + System.out.println(element); + } + } + + private static void varargs() { + String[] groceries = new String[] {"Milk", "Tomato", "Chips"}; + varargMethod(groceries); + varargMethod("Milk", "Tomato", "Chips"); + } + + private static void varargMethod(String... varargs) { + for (String element : varargs) { + System.out.println(element); + } + } + + private static void transformIntoList() { + Integer[] anArray = new Integer[] {1, 2, 3, 4, 5}; + + // Naïve implementation + List aList = new ArrayList<>(); // We create an empty list + for (int element : anArray) { + // We iterate over array's elements and add them to the list + aList.add(element); + } + + // Pretty implementation + aList = Arrays.asList(anArray); + + // Drawbacks + try { + aList.remove(0); + } catch (UnsupportedOperationException e) { + System.out.println(e.getMessage()); + } + + try { + aList.add(6); + } catch (UnsupportedOperationException e) { + System.out.println(e.getMessage()); + } + + int[] anotherArray = new int[] {1, 2, 3, 4, 5}; +// List anotherList = Arrays.asList(anotherArray); + } + + private static void transformIntoStream() { + int[] anArray = new int[] {1, 2, 3, 4, 5}; + IntStream aStream = Arrays.stream(anArray); + + Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5}; + Stream anotherStream = Arrays.stream(anotherArray, 2, 4); + } + + private static void sort() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8} + + Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8}; + Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8} + + String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"}; + Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"} + } + + private static void search() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + for (int i = 0; i < anArray.length; i++) { + if (anArray[i] == 4) { + System.out.println("Found at index " + i); + break; + } + } + + Arrays.sort(anArray); + int index = Arrays.binarySearch(anArray, 4); + System.out.println("Found at index " + index); + } + + private static void merge() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + int[] anotherArray = new int[] {10, 4, 9, 11, 2}; + + int[] resultArray = new int[anArray.length + anotherArray.length]; + for (int i = 0; i < resultArray.length; i++) { + resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]); + } + for (int element : resultArray) { + System.out.println(element); + } + + Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length])); + for (int element : resultArray) { + System.out.println(element); + } + } + +} From 247d855422fef735fd9142b63b332973cb8a2e82 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 8 Oct 2018 20:25:36 +0200 Subject: [PATCH 05/39] added article link --- spring-cloud-data-flow/etl/README.MD | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spring-cloud-data-flow/etl/README.MD b/spring-cloud-data-flow/etl/README.MD index 0cbb460b01..ee9c3a19c3 100644 --- a/spring-cloud-data-flow/etl/README.MD +++ b/spring-cloud-data-flow/etl/README.MD @@ -7,3 +7,7 @@ JDBC Source - Application Starter distributed by default customer-transform - Custom application to transform the data customer-mongodb-sink - Custom application to sink the data + +# Relevant Articles + +* [ETL with Spring Cloud Data Flow](https://www.baeldung.com/spring-cloud-data-flow-etl) From 369d471b8fa5b7b4d88a214bce56bbcd451806c3 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 8 Oct 2018 20:35:36 +0200 Subject: [PATCH 06/39] added link --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index a117d1843d..65263e4d8a 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -150,3 +150,4 @@ - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) - [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) +- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root) From 8bf1a4cdf8d59328eba36d53d5716175bd97b1d6 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 8 Oct 2018 22:24:39 +0300 Subject: [PATCH 07/39] Update FinalList.java --- .../mockito/src/test/java/org/baeldung/mockito/FinalList.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java index 3824de619c..c41021f7b6 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java @@ -1,6 +1,6 @@ package org.baeldung.mockito; -public class FinalList extends MyList { +public final class FinalList extends MyList { @Override public int size() { From e1d07fcc4c0a5940c4d7f851dd35309ef92fd888 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Thu, 11 Oct 2018 20:59:40 +0200 Subject: [PATCH 08/39] added link --- core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-8/README.md b/core-java-8/README.md index 64d423aafe..ffd629a170 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -32,3 +32,4 @@ - [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) - [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) +- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) From bae7a74acd987defc018c79852b88417f8c3a931 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Fri, 12 Oct 2018 10:54:04 +0100 Subject: [PATCH 09/39] Adding files for the article BAEL-2206 --- .../interfaces/ConflictingInterfaces.kt | 23 +++++++++++++ .../interfaces/InterfaceDelegation.kt | 13 ++++++++ .../baeldung/interfaces/MultipleInterfaces.kt | 29 +++++++++++++++++ .../baeldung/interfaces/SimpleInterface.kt | 24 ++++++++++++++ .../interfaces/InterfaceExamplesUnitTest.kt | 32 +++++++++++++++++++ 5 files changed, 121 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt new file mode 100644 index 0000000000..630afbdae7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt @@ -0,0 +1,23 @@ +package com.baeldung.interfaces + +interface BaseInterface { + fun someMethod(): String +} + +interface FirstChildInterface : BaseInterface { + override fun someMethod(): String { + return("Hello, from someMethod in FirstChildInterface") + } +} + +interface SecondChildInterface : BaseInterface { + override fun someMethod(): String { + return("Hello, from someMethod in SecondChildInterface") + } +} + +class ChildClass : FirstChildInterface, SecondChildInterface { + override fun someMethod(): String { + return super.someMethod() + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt new file mode 100644 index 0000000000..591fde0689 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt @@ -0,0 +1,13 @@ +package com.baeldung.interfaces + +interface MyInterface { + fun someMethod(): String +} + +class MyClass() : MyInterface { + override fun someMethod(): String { + return("Hello, World!") + } +} + +class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt new file mode 100644 index 0000000000..105a85cbb3 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt @@ -0,0 +1,29 @@ +package com.baeldung.interfaces + +interface FirstInterface { + fun someMethod(): String + + fun anotherMethod(): String { + return("Hello, from anotherMethod in FirstInterface") + } +} + +interface SecondInterface { + fun someMethod(): String { + return("Hello, from someMethod in SecondInterface") + } + + fun anotherMethod(): String { + return("Hello, from anotherMethod in SecondInterface") + } +} + +class SomeClass: FirstInterface, SecondInterface { + override fun someMethod(): String { + return("Hello, from someMethod in SomeClass") + } + + override fun anotherMethod(): String { + return("Hello, from anotherMethod in SomeClass") + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt new file mode 100644 index 0000000000..0758549dde --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt @@ -0,0 +1,24 @@ +package com.baeldung.interfaces + +interface SimpleInterface { + val firstProp: String + val secondProp: String + get() = "Second Property" + fun firstMethod(): String + fun secondMethod(): String { + println("Hello, from: " + secondProp) + return "" + } +} + +class SimpleClass: SimpleInterface { + override val firstProp: String = "First Property" + override val secondProp: String + get() = "Second Property, Overridden!" + override fun firstMethod(): String { + return("Hello, from: " + firstProp) + } + override fun secondMethod(): String { + return("Hello, from: " + secondProp + firstProp) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt new file mode 100644 index 0000000000..96b99948b7 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt @@ -0,0 +1,32 @@ +package com.baeldung.interfaces + +import org.junit.Test +import kotlin.test.assertEquals + +class InterfaceExamplesUnitTest { + @Test + fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() { + val simpleClass = SimpleClass() + assertEquals("Hello, from: First Property", simpleClass.firstMethod()) + assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod()) + } + + @Test + fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() { + val someClass = SomeClass() + assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod()) + assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod()) + } + + @Test + fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() { + val childClass = ChildClass() + assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod()) + } + + @Test + fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() { + val myClass = MyClass() + assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod()) + } +} \ No newline at end of file From 6b3803a683a729d356ad88bc0a0b982a587af9c3 Mon Sep 17 00:00:00 2001 From: elrisita Date: Sun, 14 Oct 2018 17:27:34 +0100 Subject: [PATCH 10/39] BAEL-2242 --- .../baeldung/removal/CollectionRemoveIf.java | 19 +++++ .../java/com/baeldung/removal/Iterators.java | 28 +++++++ .../removal/StreamFilterAndCollector.java | 23 ++++++ .../removal/StreamPartitioningBy.java | 28 +++++++ .../com/baeldung/removal/RemovalUnitTest.java | 77 +++++++++++++++++++ 5 files changed, 175 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/removal/CollectionRemoveIf.java create mode 100644 core-java-collections/src/main/java/com/baeldung/removal/Iterators.java create mode 100644 core-java-collections/src/main/java/com/baeldung/removal/StreamFilterAndCollector.java create mode 100644 core-java-collections/src/main/java/com/baeldung/removal/StreamPartitioningBy.java create mode 100644 core-java-collections/src/test/java/com/baeldung/removal/RemovalUnitTest.java diff --git a/core-java-collections/src/main/java/com/baeldung/removal/CollectionRemoveIf.java b/core-java-collections/src/main/java/com/baeldung/removal/CollectionRemoveIf.java new file mode 100644 index 0000000000..2f5e91596f --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/removal/CollectionRemoveIf.java @@ -0,0 +1,19 @@ +package com.baeldung.removal; + +import java.util.ArrayList; +import java.util.Collection; + +public class CollectionRemoveIf { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + names.removeIf(e -> e.startsWith("A")); + System.out.println(String.join(",", names)); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/removal/Iterators.java b/core-java-collections/src/main/java/com/baeldung/removal/Iterators.java new file mode 100644 index 0000000000..86b91b3fdc --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/removal/Iterators.java @@ -0,0 +1,28 @@ +package com.baeldung.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +public class Iterators { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Iterator i = names.iterator(); + + while (i.hasNext()) { + String e = i.next(); + if (e.startsWith("A")) { + i.remove(); + } + } + + System.out.println(String.join(",", names)); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/removal/StreamFilterAndCollector.java b/core-java-collections/src/main/java/com/baeldung/removal/StreamFilterAndCollector.java new file mode 100644 index 0000000000..bf6db68bae --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/removal/StreamFilterAndCollector.java @@ -0,0 +1,23 @@ +package com.baeldung.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.Collectors; + +public class StreamFilterAndCollector { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Collection filteredCollection = names + .stream() + .filter(e -> !e.startsWith("A")) + .collect(Collectors.toList()); + System.out.println(String.join(",", filteredCollection)); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/removal/StreamPartitioningBy.java b/core-java-collections/src/main/java/com/baeldung/removal/StreamPartitioningBy.java new file mode 100644 index 0000000000..c77e996616 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/removal/StreamPartitioningBy.java @@ -0,0 +1,28 @@ +package com.baeldung.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class StreamPartitioningBy { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Map> classifiedElements = names + .stream() + .collect(Collectors.partitioningBy((String e) -> !e.startsWith("A"))); + + String matching = String.join(",", classifiedElements.get(Boolean.TRUE)); + String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE)); + System.out.println("Matching elements: " + matching); + System.out.println("Non matching elements: " + nonMatching); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/removal/RemovalUnitTest.java b/core-java-collections/src/test/java/com/baeldung/removal/RemovalUnitTest.java new file mode 100644 index 0000000000..1b379f32de --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/removal/RemovalUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.removal; + +import org.junit.Before; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class RemovalUnitTest { + + Collection names; + Collection expected; + Collection removed; + + @Before + public void setupTestData() { + names = new ArrayList<>(); + expected = new ArrayList<>(); + removed = new ArrayList<>(); + + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + expected.add("John"); + expected.add("Mary"); + expected.add("Mark"); + + removed.add("Ana"); + removed.add("Anthony"); + } + + @Test + public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + Iterator i = names.iterator(); + + while (i.hasNext()) { + String e = i.next(); + if (e.startsWith("A")) { + i.remove(); + } + } + + assertThat(names, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + names.removeIf(e -> e.startsWith("A")); + assertThat(names, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + Collection filteredCollection = names + .stream() + .filter(e -> !e.startsWith("A")) + .collect(Collectors.toList()); + assertThat(filteredCollection, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() { + Map> classifiedElements = names + .stream() + .collect(Collectors.partitioningBy((String e) -> !e.startsWith("A"))); + + assertThat(classifiedElements.get(Boolean.TRUE), is(expected)); + assertThat(classifiedElements.get(Boolean.FALSE), is(removed)); + } + +} From 3a14ed0ff35556766c700a51c1d2004350db6a27 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 23:46:10 +0530 Subject: [PATCH 11/39] [BAEL-9515] - Added latest version of spring 1.5 --- parent-boot-1/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index 7742841d07..d220b4a6b7 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -17,7 +17,7 @@ org.springframework.boot spring-boot-dependencies - 1.5.15.RELEASE + 1.5.16.RELEASE pom import From 5c0ea4c47d59c0d17a1f2da5f5c181426f9a6168 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 14 Oct 2018 22:39:34 +0300 Subject: [PATCH 12/39] move tests in junit-5 --- .../{throwsexception => junit5vstestng}/Calculator.java | 2 +- .../DivideByZeroException.java | 2 +- .../CalculatorUnitTest.java | 2 +- .../baeldung/junit5vstestng}/Class1UnitTest.java | 2 +- .../baeldung/junit5vstestng}/Class2UnitTest.java | 2 +- .../baeldung/junit5vstestng}/CustomNameUnitTest.java | 2 +- .../baeldung/junit5vstestng}/ParameterizedUnitTest.java | 2 +- .../baeldung/junit5vstestng}/PizzaDeliveryStrategy.java | 2 +- .../baeldung/junit5vstestng}/SelectClassesSuiteUnitTest.java | 4 +--- .../baeldung/junit5vstestng}/SelectPackagesSuiteUnitTest.java | 2 +- ...viceIntegrationTest.java => SummationServiceUnitTest.java} | 2 +- 11 files changed, 11 insertions(+), 13 deletions(-) rename testing-modules/junit-5/src/main/java/com/baeldung/{throwsexception => junit5vstestng}/Calculator.java (85%) rename testing-modules/junit-5/src/main/java/com/baeldung/{throwsexception => junit5vstestng}/DivideByZeroException.java (79%) rename testing-modules/junit-5/src/test/java/com/baeldung/{throwsexception => junit5vstestng}/CalculatorUnitTest.java (90%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/suite/childpackage1 => com/baeldung/junit5vstestng}/Class1UnitTest.java (81%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/suite/childpackage2 => com/baeldung/junit5vstestng}/Class2UnitTest.java (81%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/customtestname => com/baeldung/junit5vstestng}/CustomNameUnitTest.java (91%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/parameterisedsource => com/baeldung/junit5vstestng}/ParameterizedUnitTest.java (96%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/parameterisedsource => com/baeldung/junit5vstestng}/PizzaDeliveryStrategy.java (57%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/suite => com/baeldung/junit5vstestng}/SelectClassesSuiteUnitTest.java (63%) rename testing-modules/junit-5/src/test/java/{org/baeldung/java/suite => com/baeldung/junit5vstestng}/SelectPackagesSuiteUnitTest.java (89%) rename testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/{SummationServiceIntegrationTest.java => SummationServiceUnitTest.java} (96%) diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/Calculator.java similarity index 85% rename from testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/Calculator.java index 50dbc9c774..4ff303c031 100644 --- a/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java +++ b/testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/Calculator.java @@ -1,4 +1,4 @@ -package com.baeldung.throwsexception; +package com.baeldung.junit5vstestng; public class Calculator { diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/DivideByZeroException.java similarity index 79% rename from testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/DivideByZeroException.java index 4413374c99..4523f46590 100644 --- a/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java +++ b/testing-modules/junit-5/src/main/java/com/baeldung/junit5vstestng/DivideByZeroException.java @@ -1,4 +1,4 @@ -package com.baeldung.throwsexception; +package com.baeldung.junit5vstestng; public class DivideByZeroException extends RuntimeException { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CalculatorUnitTest.java similarity index 90% rename from testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CalculatorUnitTest.java index ef838ed304..c563b01603 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CalculatorUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.throwsexception; +package com.baeldung.junit5vstestng; import org.junit.Test; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class1UnitTest.java similarity index 81% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class1UnitTest.java index 78469cb971..09c2b9108b 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class1UnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.suite.childpackage1; +package com.baeldung.junit5vstestng; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class2UnitTest.java similarity index 81% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class2UnitTest.java index 4463ecfad9..184ecafa1b 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/Class2UnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.suite.childpackage2; +package com.baeldung.junit5vstestng; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CustomNameUnitTest.java similarity index 91% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CustomNameUnitTest.java index f04b825c89..9cf03ad3de 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/CustomNameUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.customtestname; +package com.baeldung.junit5vstestng; import static org.junit.Assert.assertNotNull; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/ParameterizedUnitTest.java similarity index 96% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/ParameterizedUnitTest.java index 8d09161176..b5560650c4 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/ParameterizedUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.parameterisedsource; +package com.baeldung.junit5vstestng; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/PizzaDeliveryStrategy.java similarity index 57% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/PizzaDeliveryStrategy.java index ecfc7b4627..7f0a0ffa20 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/PizzaDeliveryStrategy.java @@ -1,4 +1,4 @@ -package org.baeldung.java.parameterisedsource; +package com.baeldung.junit5vstestng; public enum PizzaDeliveryStrategy { EXPRESS, diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java similarity index 63% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java index 220897eae7..7b4bd746bf 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectClassesSuiteUnitTest.java @@ -1,7 +1,5 @@ -package org.baeldung.java.suite; +package com.baeldung.junit5vstestng; -import org.baeldung.java.suite.childpackage1.Class1UnitTest; -import org.baeldung.java.suite.childpackage2.Class2UnitTest; import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.SelectClasses; import org.junit.runner.RunWith; diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java similarity index 89% rename from testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java index ae887ae43b..8f2eb2b5c5 100644 --- a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SelectPackagesSuiteUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.suite; +package com.baeldung.junit5vstestng; import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.SelectPackages; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceUnitTest.java similarity index 96% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceUnitTest.java index 92e7a6f5db..a8c02e9968 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceUnitTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class SummationServiceIntegrationTest { +public class SummationServiceUnitTest { private static List numbers; @BeforeAll From 2db4d4091e50024d9ae8e4280387858aa7245da3 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 14 Oct 2018 22:44:56 +0300 Subject: [PATCH 13/39] modify link --- core-java/README.md | 1 - testing-modules/junit-5/README.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/README.md b/core-java/README.md index 9e38dfc47d..c0c3c5c0b9 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -29,7 +29,6 @@ - [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) - [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions) -- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) - [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 836848282b..1fbd7a4a5e 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -15,3 +15,4 @@ - [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) - [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) +- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) From 6d79649b5610243216333224222bb88ce9cf6d50 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 15 Oct 2018 01:32:54 +0530 Subject: [PATCH 14/39] [BAEL-9547] - Splitted guava module and introduced guava-collections module --- guava-collections/.gitignore | 13 ++++ guava-collections/README.md | 20 ++++++ guava-collections/pom.xml | 66 ++++++++++++++++++ .../src/main/resources/logback.xml | 19 +++++ .../baeldung/guava/EvictingQueueUnitTest.java | 0 .../guava/GuavaCollectionTypesUnitTest.java | 0 .../GuavaCollectionsExamplesUnitTest.java | 0 ...avaFilterTransformCollectionsUnitTest.java | 0 .../org/baeldung/guava/GuavaMapFromSet.java | 0 .../guava/GuavaMapFromSetUnitTest.java | 0 .../guava/GuavaMapInitializeUnitTest.java | 0 .../baeldung/guava/GuavaMultiMapUnitTest.java | 0 .../guava/GuavaOrderingExamplesUnitTest.java | 0 .../baeldung/guava/GuavaOrderingUnitTest.java | 0 .../baeldung/guava/GuavaRangeMapUnitTest.java | 0 .../baeldung/guava/GuavaRangeSetUnitTest.java | 0 .../baeldung/guava/GuavaStringUnitTest.java | 0 .../guava/MinMaxPriorityQueueUnitTest.java | 0 .../hamcrest/HamcrestExamplesUnitTest.java | 0 .../CollectionApachePartitionUnitTest.java | 0 .../CollectionGuavaPartitionUnitTest.java | 0 .../java/CollectionJavaPartitionUnitTest.java | 0 .../src/test/resources/.gitignore | 13 ++++ guava-collections/src/test/resources/test.out | 1 + guava-collections/src/test/resources/test1.in | 1 + .../src/test/resources/test1_1.in | 1 + guava-collections/src/test/resources/test2.in | 4 ++ .../src/test/resources/test_copy.in | 1 + .../src/test/resources/test_le.txt | Bin 0 -> 4 bytes guava/README.md | 14 ---- guava/pom.xml | 7 -- pom.xml | 2 + 32 files changed, 141 insertions(+), 21 deletions(-) create mode 100644 guava-collections/.gitignore create mode 100644 guava-collections/README.md create mode 100644 guava-collections/pom.xml create mode 100644 guava-collections/src/main/resources/logback.xml rename {guava => guava-collections}/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapFromSet.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java (100%) create mode 100644 guava-collections/src/test/resources/.gitignore create mode 100644 guava-collections/src/test/resources/test.out create mode 100644 guava-collections/src/test/resources/test1.in create mode 100644 guava-collections/src/test/resources/test1_1.in create mode 100644 guava-collections/src/test/resources/test2.in create mode 100644 guava-collections/src/test/resources/test_copy.in create mode 100644 guava-collections/src/test/resources/test_le.txt diff --git a/guava-collections/.gitignore b/guava-collections/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/guava-collections/.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/guava-collections/README.md b/guava-collections/README.md new file mode 100644 index 0000000000..eb1eb1d35c --- /dev/null +++ b/guava-collections/README.md @@ -0,0 +1,20 @@ +========= + +## Guava and Hamcrest Cookbooks and Examples + + +### Relevant Articles: +- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) +- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) +- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) +- [Partition a List in Java](http://www.baeldung.com/java-list-split) +- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) +- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) +- [Guava – Lists](http://www.baeldung.com/guava-lists) +- [Guava – Sets](http://www.baeldung.com/guava-sets) +- [Guava – Maps](http://www.baeldung.com/guava-maps) +- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) +- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) +- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) +- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) \ No newline at end of file diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml new file mode 100644 index 0000000000..a717023156 --- /dev/null +++ b/guava-collections/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung + guava-collections + 0.1.0-SNAPSHOT + guava-collections + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.hamcrest + java-hamcrest + ${java-hamcrest.version} + test + + + + + guava + + + src/main/resources + true + + + + + + + 24.0-jre + 3.5 + 4.1 + + + 3.6.1 + 2.0.0.0 + + + \ No newline at end of file diff --git a/guava-collections/src/main/resources/logback.xml b/guava-collections/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/guava-collections/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java diff --git a/guava-collections/src/test/resources/.gitignore b/guava-collections/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/guava-collections/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/guava-collections/src/test/resources/test.out b/guava-collections/src/test/resources/test.out new file mode 100644 index 0000000000..7a79da3803 --- /dev/null +++ b/guava-collections/src/test/resources/test.out @@ -0,0 +1 @@ +John Jane Adam Tom \ No newline at end of file diff --git a/guava-collections/src/test/resources/test1.in b/guava-collections/src/test/resources/test1.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/guava-collections/src/test/resources/test1.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/guava-collections/src/test/resources/test1_1.in b/guava-collections/src/test/resources/test1_1.in new file mode 100644 index 0000000000..8318c86b35 --- /dev/null +++ b/guava-collections/src/test/resources/test1_1.in @@ -0,0 +1 @@ +Test \ No newline at end of file diff --git a/guava-collections/src/test/resources/test2.in b/guava-collections/src/test/resources/test2.in new file mode 100644 index 0000000000..622efea9e6 --- /dev/null +++ b/guava-collections/src/test/resources/test2.in @@ -0,0 +1,4 @@ +John +Jane +Adam +Tom \ No newline at end of file diff --git a/guava-collections/src/test/resources/test_copy.in b/guava-collections/src/test/resources/test_copy.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/guava-collections/src/test/resources/test_copy.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/guava-collections/src/test/resources/test_le.txt b/guava-collections/src/test/resources/test_le.txt new file mode 100644 index 0000000000000000000000000000000000000000..f7cc484bf45e18b3fe4dea78290abf122bedbad1 GIT binary patch literal 4 LcmYdcU|;|M0h9n` literal 0 HcmV?d00001 diff --git a/guava/README.md b/guava/README.md index fe1a347d72..7501bf08de 100644 --- a/guava/README.md +++ b/guava/README.md @@ -4,33 +4,19 @@ ### Relevant Articles: -- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) -- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) -- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) -- [Partition a List in Java](http://www.baeldung.com/java-list-split) -- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) -- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) -- [Guava – Lists](http://www.baeldung.com/guava-lists) -- [Guava – Sets](http://www.baeldung.com/guava-sets) -- [Guava – Maps](http://www.baeldung.com/guava-maps) - [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) - [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering) - [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions) - [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader) - [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer) - [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus) -- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) -- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) -- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) - [Guide to Guava Table](http://www.baeldung.com/guava-table) - [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection) - [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) -- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) diff --git a/guava/pom.xml b/guava/pom.xml index 60678608dd..1d37a79ab6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -14,12 +14,6 @@ - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - org.apache.commons commons-lang3 @@ -56,7 +50,6 @@ 24.0-jre 3.5 - 4.1 3.6.1 diff --git a/pom.xml b/pom.xml index 28a6dd358e..d48ec6b7cb 100644 --- a/pom.xml +++ b/pom.xml @@ -372,6 +372,7 @@ google-web-toolkit gson guava + guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 @@ -1279,6 +1280,7 @@ google-cloud gson guava + guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 From c882fa6e54cc7467caea98c2eeaaf16f1c58ae97 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 14 Oct 2018 23:40:39 +0300 Subject: [PATCH 15/39] fix boot logging modules --- pom.xml | 3 + spring-boot-disable-console-logging/README.md | 2 + .../disabling-console-jul/pom.xml | 8 ++- .../properties/DisablingConsoleJulApp.java | 0 .../DisabledConsoleRestController.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/logging.properties | 0 .../disabling-console-log4j2/pom.xml | 8 ++- .../log4j2/xml/DisablingConsoleLog4j2App.java | 0 .../DisabledConsoleRestController.java | 0 .../src/main/resources/log4j2.xml | 0 .../disabling-console-logback/pom.xml | 10 +++- .../xml/DisablingConsoleLogbackApp.java | 0 .../DisabledConsoleRestController.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/logback-spring.xml | 0 .../pom.xml | 5 +- spring-boot-logging-log4j2/README.md | 1 - spring-boot-logging-log4j2/pom.xml | 57 ++++++++++++------- .../spring-boot-logging-log4j2-app/pom.xml | 33 ----------- .../springbootlogging/LoggingController.java | 2 +- .../SpringBootLoggingApplication.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/log4j2-spring.xml | 0 .../SpringContextIntegrationTest.java | 0 25 files changed, 65 insertions(+), 64 deletions(-) create mode 100644 spring-boot-disable-console-logging/README.md rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-jul/pom.xml (85%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-jul/src/main/resources/application.properties (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-jul/src/main/resources/logging.properties (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-log4j2/pom.xml (82%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-log4j2/src/main/resources/log4j2.xml (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-logback/pom.xml (63%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-logback/src/main/resources/application.properties (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/disabling-console-logback/src/main/resources/logback-spring.xml (100%) rename {spring-boot-logging-log4j2/disabling-console-logging => spring-boot-disable-console-logging}/pom.xml (80%) delete mode 100644 spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml rename spring-boot-logging-log4j2/{spring-boot-logging-log4j2-app => }/src/main/java/com/baeldung/springbootlogging/LoggingController.java (97%) rename spring-boot-logging-log4j2/{spring-boot-logging-log4j2-app => }/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java (100%) rename spring-boot-logging-log4j2/{spring-boot-logging-log4j2-app => }/src/main/resources/application.properties (100%) rename spring-boot-logging-log4j2/{spring-boot-logging-log4j2-app => }/src/main/resources/log4j2-spring.xml (100%) rename spring-boot-logging-log4j2/{spring-boot-logging-log4j2-app => }/src/test/java/org/baeldung/SpringContextIntegrationTest.java (100%) diff --git a/pom.xml b/pom.xml index da1733d2b2..6900f902aa 100644 --- a/pom.xml +++ b/pom.xml @@ -482,6 +482,7 @@ spring-boot-mvc spring-boot-vue spring-boot-logging-log4j2 + spring-boot-disable-console-logging spring-cloud-data-flow spring-cloud spring-cloud-bus @@ -1024,6 +1025,7 @@ spring-boot-security spring-boot-mvc spring-boot-logging-log4j2 + spring-boot-disable-console-logging spring-cloud-data-flow spring-cloud spring-cloud-bus @@ -1379,6 +1381,7 @@ spring-boot-security spring-boot-mvc spring-boot-logging-log4j2 + spring-boot-disable-console-logging spring-cloud-data-flow spring-cloud spring-cloud-bus diff --git a/spring-boot-disable-console-logging/README.md b/spring-boot-disable-console-logging/README.md new file mode 100644 index 0000000000..7676bd1919 --- /dev/null +++ b/spring-boot-disable-console-logging/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Logging in Spring Boot](http://www.baeldung.com/spring-boot-logging) diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml similarity index 85% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml rename to spring-boot-disable-console-logging/disabling-console-jul/pom.xml index c3bad74352..ceac0616e9 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml @@ -3,10 +3,12 @@ 4.0.0 disabling-console-jul + + - com.baeldung - disabling-console-logging - 0.0.1-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java b/spring-boot-disable-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java rename to spring-boot-disable-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/DisablingConsoleJulApp.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java b/spring-boot-disable-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java rename to spring-boot-disable-console-logging/disabling-console-jul/src/main/java/com/baeldung/springbootlogging/disablingconsole/jul/properties/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties b/spring-boot-disable-console-logging/disabling-console-jul/src/main/resources/application.properties similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/application.properties rename to spring-boot-disable-console-logging/disabling-console-jul/src/main/resources/application.properties diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties b/spring-boot-disable-console-logging/disabling-console-jul/src/main/resources/logging.properties similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-jul/src/main/resources/logging.properties rename to spring-boot-disable-console-logging/disabling-console-jul/src/main/resources/logging.properties diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml similarity index 82% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml rename to spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml index f9b34ec7d9..d6e9a8b5e5 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml @@ -3,10 +3,12 @@ 4.0.0 disabling-console-log4j2 + + - com.baeldung - disabling-console-logging - 0.0.1-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java b/spring-boot-disable-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java rename to spring-boot-disable-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/DisablingConsoleLog4j2App.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java b/spring-boot-disable-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java rename to spring-boot-disable-console-logging/disabling-console-log4j2/src/main/java/com/baeldung/springbootlogging/disablingconsole/log4j2/xml/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml b/spring-boot-disable-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml rename to spring-boot-disable-console-logging/disabling-console-log4j2/src/main/resources/log4j2.xml diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml similarity index 63% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml rename to spring-boot-disable-console-logging/disabling-console-logback/pom.xml index 6f2170390b..f18066ea03 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml @@ -2,8 +2,16 @@ 4.0.0 com.baeldung - disabling-console-logging + spring-boot-disable-console-logging 0.0.1-SNAPSHOT disabling-console-logback + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java b/spring-boot-disable-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java rename to spring-boot-disable-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/DisablingConsoleLogbackApp.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java b/spring-boot-disable-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java rename to spring-boot-disable-console-logging/disabling-console-logback/src/main/java/com/baeldung/springbootlogging/disablingconsole/logback/xml/controllers/DisabledConsoleRestController.java diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties b/spring-boot-disable-console-logging/disabling-console-logback/src/main/resources/application.properties similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/application.properties rename to spring-boot-disable-console-logging/disabling-console-logback/src/main/resources/application.properties diff --git a/spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml b/spring-boot-disable-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml similarity index 100% rename from spring-boot-logging-log4j2/disabling-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml rename to spring-boot-disable-console-logging/disabling-console-logback/src/main/resources/logback-spring.xml diff --git a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml b/spring-boot-disable-console-logging/pom.xml similarity index 80% rename from spring-boot-logging-log4j2/disabling-console-logging/pom.xml rename to spring-boot-disable-console-logging/pom.xml index 39a4a40f12..ec84372f99 100644 --- a/spring-boot-logging-log4j2/disabling-console-logging/pom.xml +++ b/spring-boot-disable-console-logging/pom.xml @@ -1,14 +1,15 @@ 4.0.0 - disabling-console-logging + spring-boot-disable-console-logging pom Projects for Disabling Spring Boot Console Logging tutorials + parent-boot-2 com.baeldung - spring-boot-logging-log4j2 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-boot-logging-log4j2/README.md b/spring-boot-logging-log4j2/README.md index 305957ed8d..7676bd1919 100644 --- a/spring-boot-logging-log4j2/README.md +++ b/spring-boot-logging-log4j2/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Logging in Spring Boot](http://www.baeldung.com/spring-boot-logging) -- [How to Disable Console Logging in Spring Boot](https://www.baeldung.com/spring-boot-disable-console-logging) diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 7caf1e8690..7220672eaf 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -4,41 +4,58 @@ 4.0.0 spring-boot-logging-log4j2 - pom - Projects for Spring Boot Logging tutorials + jar + Demo project for Spring Boot Logging with Log4J2 + + - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 + spring-boot-starter-parent + org.springframework.boot + 2.0.5.RELEASE org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + - org.springframework.boot spring-boot-starter-test - test + + + org.springframework.boot + spring-boot-starter-log4j2 - - spring-boot-logging-log4j2-app - disabling-console-logging - - - - - org.springframework.boot - spring-boot-maven-plugin - - + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*ManualTest.java + **/*LiveTest.java + + + + - + + + + diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml b/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml deleted file mode 100644 index 571794167e..0000000000 --- a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - - spring-boot-logging-log4j2-app - jar - Demo project for Spring Boot Logging with Log4J2 - - - spring-boot-logging-log4j2 - com.baeldung - 0.0.1-SNAPSHOT - .. - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - - - diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java similarity index 97% rename from spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java rename to spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java index 07763c8c3b..d462926616 100644 --- a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/LoggingController.java +++ b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LoggingController.java @@ -32,6 +32,6 @@ public class LoggingController { loggerNative.warn("This WARN message been printed by Log4j2 without passing through SLF4J"); loggerNative.error("This ERROR message been printed by Log4j2 without passing through SLF4J"); loggerNative.fatal("This FATAL message been printed by Log4j2 without passing through SLF4J"); - return "Howdy! Check out the Logs to see the output printed directly throguh Log4j2..."; + return "Howdy! Check out the Logs to see the output printed directly through Log4j2..."; } } diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java similarity index 100% rename from spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java rename to spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/SpringBootLoggingApplication.java diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties b/spring-boot-logging-log4j2/src/main/resources/application.properties similarity index 100% rename from spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/application.properties rename to spring-boot-logging-log4j2/src/main/resources/application.properties diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml b/spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml similarity index 100% rename from spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/main/resources/log4j2-spring.xml rename to spring-boot-logging-log4j2/src/main/resources/log4j2-spring.xml diff --git a/spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-boot-logging-log4j2/spring-boot-logging-log4j2-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextIntegrationTest.java From 23c7fb4adefb98f7c4b5cacf3560f4c8daad39ea Mon Sep 17 00:00:00 2001 From: Puneet Dewan Date: Mon, 15 Oct 2018 22:50:53 +0800 Subject: [PATCH 16/39] [BAEL-2248] Add Controller Method to accept form data Add Test method in RestTemplateBasicLiveTest --- .../web/controller/FooController.java | 17 +++++++++------- .../client/RestTemplateBasicLiveTest.java | 20 ++++++++++++++++++- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java index bf26eb3292..e8cb218258 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java @@ -5,13 +5,9 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.web.dto.Foo; import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.*; @Controller public class FooController { @@ -47,7 +43,7 @@ public class FooController { } @RequestMapping(method = RequestMethod.POST, value = "/foos/new") - @ResponseStatus(HttpStatus.OK) + @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo createFoo(@RequestBody final Foo foo) { return foo; @@ -60,4 +56,11 @@ public class FooController { return id; } + @RequestMapping(method = RequestMethod.POST, value = "/foos/form") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public String submitFoo(@RequestParam("id") String id) { + return id; + } + } 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 7bcaab6a07..143aa079d5 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -26,6 +26,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; @@ -213,7 +215,23 @@ public class RestTemplateBasicLiveTest { } } - // + @Test + public void givenFooService_whenFormSubmit_thenResourceIsCreated() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map= new LinkedMultiValueMap<>(); + map.add("id", "1"); + + HttpEntity> request = new HttpEntity<>(map, headers); + + ResponseEntity response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class); + + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final String fooResponse = response.getBody(); + assertThat(fooResponse, notNullValue()); + assertThat(fooResponse, is("1")); + } private HttpHeaders prepareBasicAuthHeaders() { final HttpHeaders headers = new HttpHeaders(); From eeb5e0892b759661283d187bb800cdce6d6844a9 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 21:40:00 +0200 Subject: [PATCH 17/39] removed unnecessary Mockito and refactored test method name --- .../FindItemsBasedOnOtherStreamUnitTest.java | 180 +++++++++--------- 1 file changed, 88 insertions(+), 92 deletions(-) rename core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java => core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java (63%) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java similarity index 63% rename from core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java rename to core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java index a0dcdddd85..326ea9fbe4 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java @@ -1,93 +1,89 @@ -package findItems; - -import static org.junit.Assert.assertEquals; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Test; - -public class FindItemsBasedOnValues { - - List EmplList = new ArrayList(); - List deptList = new ArrayList(); - - public static void main(String[] args) throws ParseException { - FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly(); - } - - @Test - public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { - Integer expectedId = 1002; - - populate(EmplList, deptList); - - List filteredList = EmplList.stream() - .filter(empl -> deptList.stream() - .anyMatch(dept -> dept.getDepartment() - .equals("sales") && empl.getEmployeeId() - .equals(dept.getEmployeeId()))) - .collect(Collectors.toList()); - - assertEquals(expectedId, filteredList.get(0) - .getEmployeeId()); - } - - private void populate(List EmplList, List deptList) { - Employee employee1 = new Employee(1001, "empl1"); - Employee employee2 = new Employee(1002, "empl2"); - Employee employee3 = new Employee(1003, "empl3"); - - Collections.addAll(EmplList, employee1, employee2, employee3); - - Department department1 = new Department(1002, "sales"); - Department department2 = new Department(1003, "marketing"); - Department department3 = new Department(1004, "sales"); - - Collections.addAll(deptList, department1, department2, department3); - } -} - -class Employee { - Integer employeeId; - String employeeName; - - public Employee(Integer employeeId, String employeeName) { - super(); - this.employeeId = employeeId; - this.employeeName = employeeName; - } - - public Integer getEmployeeId() { - return employeeId; - } - - public String getEmployeeName() { - return employeeName; - } - -} - -class Department { - Integer employeeId; - String department; - - public Department(Integer employeeId, String department) { - super(); - this.employeeId = employeeId; - this.department = department; - } - - public Integer getEmployeeId() { - return employeeId; - } - - public String getDepartment() { - return department; - } - +package com.baeldung.findItems; + +import static org.junit.Assert.assertEquals; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class FindItemsBasedOnOtherStreamUnitTest { + + private List employeeList = new ArrayList(); + + private List departmentList = new ArrayList(); + + @Test + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; + + populate(employeeList, departmentList); + + List filteredList = employeeList.stream() + .filter(empl -> departmentList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) + .collect(Collectors.toList()); + + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); + } + + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); + + Collections.addAll(EmplList, employee1, employee2, employee3); + + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); + + Collections.addAll(deptList, department1, department2, department3); + } +} + +class Employee { + private Integer employeeId; + private String employeeName; + + Employee(Integer employeeId, String employeeName) { + super(); + this.employeeId = employeeId; + this.employeeName = employeeName; + } + + Integer getEmployeeId() { + return employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + +} + +class Department { + private Integer employeeId; + private String department; + + Department(Integer employeeId, String department) { + super(); + this.employeeId = employeeId; + this.department = department; + } + + Integer getEmployeeId() { + return employeeId; + } + + String getDepartment() { + return department; + } + } \ No newline at end of file From 8cfa575f5d80ae73bafa9abe4bc4253dbe72db90 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 21:40:50 +0200 Subject: [PATCH 18/39] removed unneccessary folder --- core-java-8/findItemsBasedOnValues/.gitignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 core-java-8/findItemsBasedOnValues/.gitignore diff --git a/core-java-8/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore deleted file mode 100644 index ae3c172604..0000000000 --- a/core-java-8/findItemsBasedOnValues/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ From 5e791c56a1a5e8165a332c0f9ac83358a0706441 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 23:12:19 +0200 Subject: [PATCH 19/39] removed unneccessary folder --- .../com/baeldung/modulo/ModuloUnitTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java b/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java new file mode 100644 index 0000000000..8b3685adf3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.modulo; + +import org.junit.Test; +import static org.assertj.core.api.Java6Assertions.*; + +public class ModuloUnitTest { + + @Test + public void whenIntegerDivision_thenLosesRemainder(){ + assertThat(11 / 4).isEqualTo(2); + } + + @Test + public void whenDoubleDivision_thenKeepsRemainder(){ + assertThat(11 / 4.0).isEqualTo(2.75); + } + + @Test + public void whenModulo_thenReturnsRemainder(){ + assertThat(11 % 4).isEqualTo(3); + } + + @Test(expected = ArithmeticException.class) + public void whenDivisionByZero_thenArithmeticException(){ + double result = 1 / 0; + } + + @Test(expected = ArithmeticException.class) + public void whenModuloByZero_thenArithmeticException(){ + double result = 1 % 0; + } + + @Test + public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){ + assertThat(3 % 2).isEqualTo(1); + } + + @Test + public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){ + assertThat(4 % 2).isEqualTo(0); + } + + @Test + public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){ + int QUEUE_CAPACITY= 10; + int[] circularQueue = new int[QUEUE_CAPACITY]; + int itemsInserted = 0; + for (int value = 0; value < 1000; value++) { + int writeIndex = ++itemsInserted % QUEUE_CAPACITY; + circularQueue[writeIndex] = value; + } + } + +} From 45194b5edc1b18ca785aeaf62e0530cc4ed21293 Mon Sep 17 00:00:00 2001 From: rozagerardo Date: Tue, 16 Oct 2018 02:22:19 -0300 Subject: [PATCH 20/39] [BAEL-1502] spring-5-reactive | Validation for Functional Endpoints (#5437) * Added validation for functional endpoints scenarios: * validating in handler explicitly * created abstract handler with validation steps * using validation handlers with two implementations * * added annotated entity to be used with springvalidator * * added tests and cleaning the code slightly --- .../FunctionalValidationsApplication.java | 12 ++ .../handlers/AbstractValidationHandler.java | 45 +++++++ .../handlers/FunctionalHandler.java | 43 +++++++ ...notatedRequestEntityValidationHandler.java | 30 +++++ .../CustomRequestEntityValidationHandler.java | 37 ++++++ .../impl/OtherEntityValidationHandler.java | 28 +++++ .../model/AnnotatedRequestEntity.java | 23 ++++ .../functional/model/CustomRequestEntity.java | 17 +++ .../functional/model/OtherEntity.java | 17 +++ .../routers/ValidationsRouters.java | 29 +++++ .../CustomRequestEntityValidator.java | 29 +++++ .../validators/OtherEntityValidator.java | 27 +++++ ...FunctionalEndpointValidationsLiveTest.java | 111 ++++++++++++++++++ 13 files changed, 448 insertions(+) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java new file mode 100644 index 0000000000..e548e33c85 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.validations.functional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FunctionalValidationsApplication { + + public static void main(String[] args) { + SpringApplication.run(FunctionalValidationsApplication.class, args); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java new file mode 100644 index 0000000000..f34c1ee8d8 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java @@ -0,0 +1,45 @@ +package com.baeldung.validations.functional.handlers; + +import org.springframework.http.HttpStatus; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.ResponseStatusException; + +import reactor.core.publisher.Mono; + +public abstract class AbstractValidationHandler { + + private final Class validationClass; + + private final U validator; + + protected AbstractValidationHandler(Class clazz, U validator) { + this.validationClass = clazz; + this.validator = validator; + } + + abstract protected Mono processBody(T validBody, final ServerRequest originalRequest); + + public final Mono handleRequest(final ServerRequest request) { + return request.bodyToMono(this.validationClass) + .flatMap(body -> { + Errors errors = new BeanPropertyBindingResult(body, this.validationClass.getName()); + this.validator.validate(body, errors); + + if (errors == null || errors.getAllErrors() + .isEmpty()) { + return processBody(body, request); + } else { + return onValidationErrors(errors, body, request); + } + }); + } + + protected Mono onValidationErrors(Errors errors, T invalidBody, final ServerRequest request) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors() + .toString()); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java new file mode 100644 index 0000000000..d7e3bd0bc0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java @@ -0,0 +1,43 @@ +package com.baeldung.validations.functional.handlers; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.ResponseStatusException; + +import com.baeldung.validations.functional.model.CustomRequestEntity; +import com.baeldung.validations.functional.validators.CustomRequestEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class FunctionalHandler { + + public Mono handleRequest(final ServerRequest request) { + Validator validator = new CustomRequestEntityValidator(); + Mono responseBody = request.bodyToMono(CustomRequestEntity.class) + .map(body -> { + Errors errors = new BeanPropertyBindingResult(body, CustomRequestEntity.class.getName()); + validator.validate(body, errors); + + if (errors == null || errors.getAllErrors() + .isEmpty()) { + return String.format("Hi, %s [%s]!", body.getName(), body.getCode()); + + } else { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors() + .toString()); + } + + }); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(responseBody, String.class); + + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java new file mode 100644 index 0000000000..2011679741 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.AnnotatedRequestEntity; + +import reactor.core.publisher.Mono; + +@Component +public class AnnotatedRequestEntityValidationHandler extends AbstractValidationHandler { + + private AnnotatedRequestEntityValidationHandler(@Autowired Validator validator) { + super(AnnotatedRequestEntity.class, validator); + } + + @Override + protected Mono processBody(AnnotatedRequestEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Hi, %s. Password: %s!", validBody.getUser(), validBody.getPassword()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java new file mode 100644 index 0000000000..34630c60b2 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java @@ -0,0 +1,37 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.CustomRequestEntity; +import com.baeldung.validations.functional.validators.CustomRequestEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class CustomRequestEntityValidationHandler extends AbstractValidationHandler { + + private CustomRequestEntityValidationHandler() { + super(CustomRequestEntity.class, new CustomRequestEntityValidator()); + } + + @Override + protected Mono processBody(CustomRequestEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Hi, %s [%s]!", validBody.getName(), validBody.getCode()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } + + @Override + protected Mono onValidationErrors(Errors errors, CustomRequestEntity invalidBody, final ServerRequest request) { + return ServerResponse.badRequest() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(String.format("Custom message showing the errors: %s", errors.getAllErrors() + .toString())), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java new file mode 100644 index 0000000000..0196287d13 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.OtherEntity; +import com.baeldung.validations.functional.validators.OtherEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class OtherEntityValidationHandler extends AbstractValidationHandler { + + private OtherEntityValidationHandler() { + super(OtherEntity.class, new OtherEntityValidator()); + } + + @Override + protected Mono processBody(OtherEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Other object with item %s and quantity %s!", validBody.getItem(), validBody.getQuantity()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java new file mode 100644 index 0000000000..992f07481c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java @@ -0,0 +1,23 @@ +package com.baeldung.validations.functional.model; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class AnnotatedRequestEntity { + @NotNull + private String user; + + @NotNull + @Size(min = 4, max = 7) + private String password; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java new file mode 100644 index 0000000000..ed459f121b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java @@ -0,0 +1,17 @@ +package com.baeldung.validations.functional.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class CustomRequestEntity { + + private String name; + private String code; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java new file mode 100644 index 0000000000..78667cb13d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java @@ -0,0 +1,17 @@ +package com.baeldung.validations.functional.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class OtherEntity { + + private String item; + private Integer quantity; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java new file mode 100644 index 0000000000..efbdbe3f99 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java @@ -0,0 +1,29 @@ +package com.baeldung.validations.functional.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.FunctionalHandler; +import com.baeldung.validations.functional.handlers.impl.AnnotatedRequestEntityValidationHandler; +import com.baeldung.validations.functional.handlers.impl.CustomRequestEntityValidationHandler; +import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHandler; + +@Configuration +public class ValidationsRouters { + + @Bean + public RouterFunction responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler, + @Autowired FunctionalHandler complexHandler, + @Autowired OtherEntityValidationHandler otherHandler, + @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) { + return RouterFunctions.route(RequestPredicates.POST("/complex-handler-functional-validation"), complexHandler::handleRequest) + .andRoute(RequestPredicates.POST("/dry-functional-validation"), dryHandler::handleRequest) + .andRoute(RequestPredicates.POST("/other-dry-functional-validation"), otherHandler::handleRequest) + .andRoute(RequestPredicates.POST("/annotated-functional-validation"), annotatedEntityHandler::handleRequest); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java new file mode 100644 index 0000000000..085d477318 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.validations.functional.validators; + +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.validations.functional.model.CustomRequestEntity; + +public class CustomRequestEntityValidator implements Validator { + + private static final int MINIMUM_CODE_LENGTH = 6; + + @Override + public boolean supports(Class clazz) { + return CustomRequestEntity.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required"); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "field.required"); + CustomRequestEntity request = (CustomRequestEntity) target; + if (request.getCode() != null && request.getCode() + .trim() + .length() < MINIMUM_CODE_LENGTH) { + errors.rejectValue("code", "field.min.length", new Object[] { Integer.valueOf(MINIMUM_CODE_LENGTH) }, "The code must be at least [" + MINIMUM_CODE_LENGTH + "] characters in length."); + } + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java new file mode 100644 index 0000000000..18c2c28cfe --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java @@ -0,0 +1,27 @@ +package com.baeldung.validations.functional.validators; + +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.validations.functional.model.OtherEntity; + +public class OtherEntityValidator implements Validator { + + private static final int MIN_ITEM_QUANTITY = 1; + + @Override + public boolean supports(Class clazz) { + return OtherEntity.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "item", "field.required"); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "quantity", "field.required"); + OtherEntity request = (OtherEntity) target; + if (request.getQuantity() != null && request.getQuantity() < MIN_ITEM_QUANTITY) { + errors.rejectValue("quantity", "field.min.length", new Object[] { Integer.valueOf(MIN_ITEM_QUANTITY) }, "There must be at least one item"); + } + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java new file mode 100644 index 0000000000..5fe764bf8f --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java @@ -0,0 +1,111 @@ +package com.baeldung.validations.functional; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +import com.baeldung.validations.functional.model.AnnotatedRequestEntity; +import com.baeldung.validations.functional.model.CustomRequestEntity; + +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class FunctionalEndpointValidationsLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + private static final String COMPLEX_EP_URL = BASE_URL + "/complex-handler-functional-validation"; + private static final String DRY_EP_URL = BASE_URL + "/dry-functional-validation"; + private static final String ANNOTATIONS_EP_URL = BASE_URL + "/annotated-functional-validation"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void whenRequestingDryEPWithInvalidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "123"); + + ResponseSpec response = client.post() + .uri(DRY_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingComplexEPWithInvalidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "123"); + + ResponseSpec response = client.post() + .uri(COMPLEX_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingAnnotatedEPWithInvalidBody_thenObtainBadRequest() { + AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "passwordlongerthan7digits"); + + ResponseSpec response = client.post() + .uri(ANNOTATIONS_EP_URL) + .body(Mono.just(body), AnnotatedRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingDryEPWithValidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "1234567"); + + ResponseSpec response = client.post() + .uri(DRY_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } + + @Test + public void whenRequestingComplexEPWithValidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "1234567"); + + ResponseSpec response = client.post() + .uri(COMPLEX_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } + + @Test + public void whenRequestingAnnotatedEPWithValidBody_thenObtainBadRequest() { + AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "12345"); + + ResponseSpec response = client.post() + .uri(ANNOTATIONS_EP_URL) + .body(Mono.just(body), AnnotatedRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } +} From 201c3a75c89827e3b848dcb730657739129a56ee Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 16 Oct 2018 23:22:04 +0530 Subject: [PATCH 21/39] BAEL-9467 Update Spring Security article - Migrated module to inherit from spring-5 and spring-security-5 - Relevant changes and fixes in code for upgraded spring-security module --- spring-security-rest/pom.xml | 21 ++--- .../org/baeldung/persistence/model/Foo.java | 2 + ...uestAwareAuthenticationSuccessHandler.java | 7 +- .../RestAuthenticationEntryPoint.java | 6 +- .../org/baeldung/spring/ClientWebConfig.java | 11 +-- .../baeldung/spring/SecurityJavaConfig.java | 77 ++++++++++--------- .../org/baeldung/spring/SwaggerConfig.java | 15 +++- .../java/org/baeldung/spring/WebConfig.java | 9 +-- .../web/controller/AsyncController.java | 4 +- .../web/controller/CustomerController.java | 4 +- .../web/controller/FooController.java | 11 --- .../web/service/AsyncServiceImpl.java | 6 +- .../src/main/resources/webSecurityConfig.xml | 6 +- 13 files changed, 84 insertions(+), 95 deletions(-) diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 57ce5ddb92..70967ce214 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -2,7 +2,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-security-rest 0.1-SNAPSHOT spring-security-rest @@ -10,9 +9,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -195,13 +194,6 @@ - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - org.codehaus.cargo cargo-maven2-plugin @@ -282,17 +274,17 @@ - 4.2.6.RELEASE - 0.21.0.RELEASE + 5.1.0.RELEASE + 0.25.0.RELEASE 3.1.0 1.1.0.Final 1.2 - 2.8.5 + 2.9.2 - 19.0 + 26.0-jre 3.5 1.3.2 @@ -303,7 +295,6 @@ 2.9.2 - 2.6 1.6.1 diff --git a/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java index 1941e2aa51..05a7c7b9a0 100644 --- a/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java @@ -6,6 +6,8 @@ import javax.validation.constraints.Size; public class Foo implements Serializable { + private static final long serialVersionUID = -5422285893276747592L; + private long id; @Size(min = 5, max = 14) diff --git a/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java index f4b8e7f5ac..6018264632 100644 --- a/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -11,8 +11,10 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationSu import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; +import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +@Component public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private RequestCache requestCache = new HttpSessionRequestCache(); @@ -33,11 +35,6 @@ public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAu } clearAuthenticationAttributes(request); - - // Use the DefaultSavedRequest URL - // final String targetUrl = savedRequest.getRedirectUrl(); - // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl); - // getRedirectStrategy().sendRedirect(request, response, targetUrl); } public void setRequestCache(final RequestCache requestCache) { diff --git a/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java b/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java index 77aa32ff97..e448e6537f 100644 --- a/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java +++ b/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java @@ -16,7 +16,11 @@ import org.springframework.stereotype.Component; public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { + public void commence( + final HttpServletRequest request, + final HttpServletResponse response, + final AuthenticationException authException) throws IOException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java index 601ba66330..8e20358a5a 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java @@ -2,16 +2,9 @@ package org.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableWebMvc @Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { - - public ClientWebConfig() { - super(); - } - - // API - +public class ClientWebConfig implements WebMvcConfigurer { } \ No newline at end of file diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java index c3e738297a..d5111f9b20 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java @@ -1,6 +1,7 @@ package org.baeldung.spring; import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler; +import org.baeldung.security.RestAuthenticationEntryPoint; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -12,6 +13,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; @Configuration @@ -20,59 +23,61 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa @ComponentScan("org.baeldung.security") public class SecurityJavaConfig extends WebSecurityConfigurerAdapter { + @Autowired + private PasswordEncoder encoder; + @Autowired private CustomAccessDeniedHandler accessDeniedHandler; - // @Autowired - // private RestAuthenticationEntryPoint restAuthenticationEntryPoint; + @Autowired + private RestAuthenticationEntryPoint restAuthenticationEntryPoint; - // @Autowired - // private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler; + @Autowired + private MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler; + + private SimpleUrlAuthenticationFailureHandler myFailureHandler = new SimpleUrlAuthenticationFailureHandler(); public SecurityJavaConfig() { super(); SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); } - // - @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("temporary").password("temporary").roles("ADMIN").and().withUser("user").password("userPass").roles("USER"); + auth.inMemoryAuthentication() + .withUser("admin").password(encoder.encode("adminPass")).roles("ADMIN") + .and() + .withUser("user").password(encoder.encode("userPass")).roles("USER"); } @Override - protected void configure(final HttpSecurity http) throws Exception {// @formatter:off - http - .csrf().disable() - .authorizeRequests() - .and() - .exceptionHandling().accessDeniedHandler(accessDeniedHandler) - // .authenticationEntryPoint(restAuthenticationEntryPoint) - .and() - .authorizeRequests() - .antMatchers("/api/csrfAttacker*").permitAll() - .antMatchers("/api/customer/**").permitAll() - .antMatchers("/api/foos/**").authenticated() - .antMatchers("/api/async/**").permitAll() - .antMatchers("/api/admin/**").hasRole("ADMIN") - .and() - .httpBasic() -// .and() -// .successHandler(authenticationSuccessHandler) -// .failureHandler(new SimpleUrlAuthenticationFailureHandler()) - .and() - .logout(); - } // @formatter:on - - @Bean - public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() { - return new MySavedRequestAwareAuthenticationSuccessHandler(); + protected void configure(final HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .and() + .exceptionHandling() + .accessDeniedHandler(accessDeniedHandler) + .authenticationEntryPoint(restAuthenticationEntryPoint) + .and() + .authorizeRequests() + .antMatchers("/api/csrfAttacker*").permitAll() + .antMatchers("/api/customer/**").permitAll() + .antMatchers("/api/foos/**").authenticated() + .antMatchers("/api/async/**").permitAll() + .antMatchers("/api/admin/**").hasRole("ADMIN") + .and() + .formLogin() + .successHandler(mySuccessHandler) + .failureHandler(myFailureHandler) + .and() + .httpBasic() + .and() + .logout(); } - + @Bean - public SimpleUrlAuthenticationFailureHandler myFailureHandler() { - return new SimpleUrlAuthenticationFailureHandler(); + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); } } \ No newline at end of file diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java index bcf6657eee..aa00e8455e 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java @@ -24,8 +24,19 @@ public class SwaggerConfig { @Bean public Docket api() { - return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")).paths(PathSelectors.ant("/foos/*")).build().apiInfo(apiInfo()).useDefaultResponseMessages(false) - .globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500).message("500 message").responseModel(new ModelRef("Error")).build(), new ResponseMessageBuilder().code(403).message("Forbidden!!!!!").build())); + return new Docket(DocumentationType.SWAGGER_2).select() + .apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")) + .paths(PathSelectors.ant("/foos/*")) + .build() + .apiInfo(apiInfo()) + .useDefaultResponseMessages(false) + .globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500) + .message("500 message") + .responseModel(new ModelRef("Error")) + .build(), + new ResponseMessageBuilder().code(403) + .message("Forbidden!!!!!") + .build())); } private ApiInfo apiInfo() { diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java index 92a3c548a2..dba07dc4e5 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java @@ -8,18 +8,14 @@ import org.springframework.web.servlet.ViewResolver; 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.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("org.baeldung.web") @EnableWebMvc @EnableAsync -public class WebConfig extends WebMvcConfigurerAdapter { - - public WebConfig() { - super(); - } +public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { @@ -38,7 +34,6 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/csrfAttacker.html"); } diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java index 456eeaaeac..f6f1c392cb 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java @@ -24,9 +24,9 @@ public class AsyncController { @RequestMapping(method = RequestMethod.GET, value = "/async") @ResponseBody public Object standardProcessing() throws Exception { - log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + log.info("Outside the @Async logic - before the async call: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); asyncService.asyncCall(); - log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + log.info("Inside the @Async logic - after the async call: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java index b8f67960f5..e1db105d18 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java @@ -48,7 +48,7 @@ public class CustomerController { } Link link =linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel(); - Resources result = new Resources(orders,link); + Resources result = new Resources<>(orders,link); return result; } @@ -67,7 +67,7 @@ public class CustomerController { } Link link =linkTo(CustomerController.class).withSelfRel(); - Resources result = new Resources(allCustomers,link); + Resources result = new Resources<>(allCustomers,link); return result; } diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java index 3b9e5d25c0..f914f82215 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -7,8 +7,6 @@ import java.util.List; import javax.servlet.http.HttpServletResponse; import org.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -25,17 +23,9 @@ import com.google.common.collect.Lists; @RequestMapping(value = "/foos") public class FooController { - @Autowired - private ApplicationEventPublisher eventPublisher; - - public FooController() { - super(); - } - // API // read - single - @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public Foo findById(@PathVariable("id") final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { @@ -43,7 +33,6 @@ public class FooController { } // read - multiple - @RequestMapping(method = RequestMethod.GET) @ResponseBody public List findAll() { diff --git a/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java b/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java index caaaa8e0dc..d6d7f53dd7 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/service/AsyncServiceImpl.java @@ -17,18 +17,18 @@ public class AsyncServiceImpl implements AsyncService { @Async @Override public void asyncCall() { - log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + log.info("Inside the @Async logic: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); } @Override public Callable checkIfPrincipalPropagated() { Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - log.info("Before new thread: " + before); + log.info("Before new thread: {}", before); return new Callable() { public Boolean call() throws Exception { Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - log.info("New thread: " + after); + log.info("New thread: {}", after); return before == after; } }; diff --git a/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-rest/src/main/resources/webSecurityConfig.xml index 4bb208a195..54bd0f91b9 100644 --- a/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -9,6 +9,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> + + + @@ -44,5 +46,5 @@ - +--> \ No newline at end of file From 2f01b4305630a8b3d1d3b124f9b2fd30a77d2f4f Mon Sep 17 00:00:00 2001 From: azrairshad Date: Wed, 17 Oct 2018 10:06:37 -0400 Subject: [PATCH 22/39] BAEL-1547: Request method not supported - 405, examples. (#5464) --- .../controller/RequestMethodController.java | 25 +++++++++++++++++ .../exception/InvalidRequestException.java | 26 ++++++++++++++++++ .../spring/service/EmployeeService.java | 12 +++++++++ .../spring/service/EmployeeServiceImpl.java | 27 +++++++++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java create mode 100644 spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java new file mode 100644 index 0000000000..03cf729ddf --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestMethodController.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.controller; + +import com.baeldung.spring.domain.Employee; +import com.baeldung.spring.exception.InvalidRequestException; +import com.baeldung.spring.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping(value="/api") +public class RequestMethodController { + + @Autowired + EmployeeService service; + + @RequestMapping(value = "/employees", produces = "application/json", method={RequestMethod.GET,RequestMethod.POST}) + public List findEmployees() + throws InvalidRequestException { + return service.getEmployeeList(); + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java new file mode 100644 index 0000000000..4dcbe86735 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/exception/InvalidRequestException.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.exception; + +public class InvalidRequestException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 4088649120307193208L; + + public InvalidRequestException() { + super(); + } + + public InvalidRequestException(final String message, final Throwable cause) { + super(message, cause); + } + + public InvalidRequestException(final String message) { + super(message); + } + + public InvalidRequestException(final Throwable cause) { + super(cause); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java new file mode 100644 index 0000000000..4d87352c42 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeService.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.service; + +import com.baeldung.spring.domain.Employee; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface EmployeeService { + + List getEmployeeList(); +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java new file mode 100644 index 0000000000..18f2d70795 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/service/EmployeeServiceImpl.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.service; + +import com.baeldung.spring.domain.Employee; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class EmployeeServiceImpl implements EmployeeService{ + + @Override + public List getEmployeeList() { + List employeeList = new ArrayList<>(); + employeeList.add(createEmployee(100L, "Steve Martin", "333-777-999")); + employeeList.add(createEmployee(200L, "Adam Schawn", "444-111-777")); + return employeeList; + } + + private Employee createEmployee(long id, String name, String contactNumber) { + Employee employee = new Employee(); + employee.setId(id); + employee.setName(name); + employee.setContactNumber(contactNumber); + return employee; + } +} From 6cabd68be52d97a55a7d0e71b757dd50344c0289 Mon Sep 17 00:00:00 2001 From: shreyasm Date: Wed, 17 Oct 2018 19:39:26 +0530 Subject: [PATCH 23/39] BAEL-2000 - Shreyas Mahajan - Adding a project for demonstrating Spring Boot Jib Maven Plugin (#5375) * BAEL-2000 - Shreyas Mahajan - Adding a project for demonstrating Spring Boot Jib Maven Plugin * BAEL-2000 - Shreyas Mahajan - Incorporating the changes * BAEL-2000 - Shreyas Mahajan - Renaming the module from spring-boot-jib to jib --- jib/pom.xml | 57 +++++++++++++++++++ .../main/java/com/baeldung/Application.java | 12 ++++ jib/src/main/java/com/baeldung/Greeting.java | 20 +++++++ .../java/com/baeldung/GreetingController.java | 20 +++++++ 4 files changed, 109 insertions(+) create mode 100644 jib/pom.xml create mode 100644 jib/src/main/java/com/baeldung/Application.java create mode 100644 jib/src/main/java/com/baeldung/Greeting.java create mode 100644 jib/src/main/java/com/baeldung/GreetingController.java diff --git a/jib/pom.xml b/jib/pom.xml new file mode 100644 index 0000000000..e71250f157 --- /dev/null +++ b/jib/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + jib + 0.1-SNAPSHOT + jib + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.google.cloud.tools + jib-maven-plugin + 0.9.10 + + + registry.hub.docker.com/baeldungjib/jib-spring-boot-app + + + + + + + + + spring-releases + https://repo.spring.io/libs-release + + + + + spring-releases + https://repo.spring.io/libs-release + + + diff --git a/jib/src/main/java/com/baeldung/Application.java b/jib/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..8c087476bf --- /dev/null +++ b/jib/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/jib/src/main/java/com/baeldung/Greeting.java b/jib/src/main/java/com/baeldung/Greeting.java new file mode 100644 index 0000000000..62834d9752 --- /dev/null +++ b/jib/src/main/java/com/baeldung/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung; + +public class Greeting { + + private final long id; + private final String content; + + public Greeting(long id, String content) { + this.id = id; + this.content = content; + } + + public long getId() { + return id; + } + + public String getContent() { + return content; + } +} \ No newline at end of file diff --git a/jib/src/main/java/com/baeldung/GreetingController.java b/jib/src/main/java/com/baeldung/GreetingController.java new file mode 100644 index 0000000000..0b082b0001 --- /dev/null +++ b/jib/src/main/java/com/baeldung/GreetingController.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.atomic.AtomicLong; + +@RestController +public class GreetingController { + + private static final String template = "Hello Docker, %s!"; + private final AtomicLong counter = new AtomicLong(); + + @GetMapping("/greeting") + public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { + return new Greeting(counter.incrementAndGet(), + String.format(template, name)); + } +} \ No newline at end of file From 99d309b8c23e6810ef47e42a3513ef08633bd6ce Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Wed, 17 Oct 2018 14:29:47 -0300 Subject: [PATCH 24/39] BAEL-2237 Using Jackson to parse XML and return JSON (#5478) --- .../jackson/xmlToJson/XmlToJsonUnitTest.java | 43 +++++++------------ 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java index 295bb9d6e8..6329a8ed2f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/xmlToJson/XmlToJsonUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.jackson.xmlToJson; - -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; @@ -14,43 +12,32 @@ import java.io.IOException; public class XmlToJsonUnitTest { @Test - public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() { + public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{ String flowerXML = "PoppyRED9"; - try { - XmlMapper xmlMapper = new XmlMapper(); - Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); + XmlMapper xmlMapper = new XmlMapper(); + Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); - assertEquals(poppy.getName(), "Poppy"); - assertEquals(poppy.getColor(), Color.RED); - assertEquals(poppy.getPetals(), new Integer(9)); + assertEquals(poppy.getName(), "Poppy"); + assertEquals(poppy.getColor(), Color.RED); + assertEquals(poppy.getPetals(), new Integer(9)); - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(poppy); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(poppy); - assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); - System.out.println(json); - } catch(IOException e) { - e.printStackTrace(); - } + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); } @Test - public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() { + public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException { String flowerXML = "PoppyRED9"; - try { - XmlMapper xmlMapper = new XmlMapper(); - JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); + XmlMapper xmlMapper = new XmlMapper(); + JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); - ObjectMapper jsonMapper = new ObjectMapper(); - String json = jsonMapper.writeValueAsString(node); + ObjectMapper jsonMapper = new ObjectMapper(); + String json = jsonMapper.writeValueAsString(node); - System.out.println(json); - - assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); - } catch(IOException e) { - e.printStackTrace(); - } + assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); } } From ad0eb1ee7d7fe65aeeeba426034d83ad04716797 Mon Sep 17 00:00:00 2001 From: vizsoro Date: Wed, 17 Oct 2018 20:02:53 +0200 Subject: [PATCH 25/39] bael-2195 lombok builder default --- lombok/pom.xml | 1 + .../lombok/builder/defaultvalue/Pojo.java | 17 +++++++++++++ .../BuilderWithDefaultValueUnitTest.java | 25 +++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/defaultvalue/Pojo.java create mode 100644 lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java diff --git a/lombok/pom.xml b/lombok/pom.xml index eba140122a..7ad2e3dc83 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -59,6 +59,7 @@ ${project.basedir}/src/main/java + ${project.build.directory}/delombok false skip diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/defaultvalue/Pojo.java b/lombok/src/main/java/com/baeldung/lombok/builder/defaultvalue/Pojo.java new file mode 100644 index 0000000000..feaade9cd5 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/defaultvalue/Pojo.java @@ -0,0 +1,17 @@ +package com.baeldung.lombok.builder.defaultvalue; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class Pojo { + private String name = "foo"; + private boolean original = true; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java new file mode 100644 index 0000000000..d9184f605c --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/defaultvalue/BuilderWithDefaultValueUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.lombok.builder.defaultvalue; + +import org.junit.Assert; +import org.junit.Test; + +public class BuilderWithDefaultValueUnitTest { + + @Test + public void givenBuilderWithDefaultValue_ThanDefaultValueIsPresent() { + Pojo build = new Pojo().toBuilder() + .build(); + Assert.assertEquals("foo", build.getName()); + Assert.assertTrue(build.isOriginal()); + } + + @Test + public void givenBuilderWithDefaultValue_NoArgsWorksAlso() { + Pojo build = new Pojo().toBuilder() + .build(); + Pojo pojo = new Pojo(); + Assert.assertEquals(build.getName(), pojo.getName()); + Assert.assertTrue(build.isOriginal() == pojo.isOriginal()); + } + +} From 03065a43e9f0652a6d64778d651779712ffcda05 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Wed, 17 Oct 2018 21:54:35 +0200 Subject: [PATCH 26/39] moving heap sort from core-java to algorithms (#5475) --- .../src/main/java/com/baeldung/algorithms}/heapsort/Heap.java | 2 +- .../java/com/baeldung/algorithms}/heapsort/HeapUnitTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename {core-java/src/main/java/com/baeldung => algorithms/src/main/java/com/baeldung/algorithms}/heapsort/Heap.java (98%) rename {core-java/src/test/java/com/baeldung => algorithms/src/test/java/com/baeldung/algorithms}/heapsort/HeapUnitTest.java (95%) diff --git a/core-java/src/main/java/com/baeldung/heapsort/Heap.java b/algorithms/src/main/java/com/baeldung/algorithms/heapsort/Heap.java similarity index 98% rename from core-java/src/main/java/com/baeldung/heapsort/Heap.java rename to algorithms/src/main/java/com/baeldung/algorithms/heapsort/Heap.java index 95e0e1d8cd..8c98e4fc5c 100644 --- a/core-java/src/main/java/com/baeldung/heapsort/Heap.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/heapsort/Heap.java @@ -1,4 +1,4 @@ -package com.baeldung.heapsort; +package com.baeldung.algorithms.heapsort; import java.util.ArrayList; import java.util.Arrays; diff --git a/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java index cc3e49b6c9..96e4936eaf 100644 --- a/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.heapsort; +package com.baeldung.algorithms.heapsort; import static org.assertj.core.api.Assertions.assertThat; From 831cdf2bd6a3f256e5fd5080536269c6b9657bbd Mon Sep 17 00:00:00 2001 From: Paul van Gool Date: Wed, 17 Oct 2018 13:00:14 -0700 Subject: [PATCH 27/39] BAEL-1215: Introduction to the Suanshu math library (#5469) * BAEL-1215: Introduction to the Suanshu math library * Updated examples based on feedback. --- libraries/pom.xml | 13 ++ .../com/baeldung/suanshu/SuanShuMath.java | 142 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/suanshu/SuanShuMath.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 6bbe8e6f1c..8ffd33272d 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -711,6 +711,12 @@ ${snakeyaml.version} + + com.numericalmethod + suanshu + ${suanshu.version} + + @@ -731,6 +737,12 @@ Apache Staging https://repository.apache.org/content/groups/staging + + nm-repo + Numerical Method's Maven Repository + http://repo.numericalmethod.com/maven/ + default + @@ -835,6 +847,7 @@ + 4.0.0 1.21 1.23.0 0.1.0 diff --git a/libraries/src/main/java/com/baeldung/suanshu/SuanShuMath.java b/libraries/src/main/java/com/baeldung/suanshu/SuanShuMath.java new file mode 100644 index 0000000000..46af24692d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/suanshu/SuanShuMath.java @@ -0,0 +1,142 @@ +package com.baeldung.suanshu; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.Matrix; +import com.numericalmethod.suanshu.algebra.linear.vector.doubles.Vector; +import com.numericalmethod.suanshu.algebra.linear.vector.doubles.dense.DenseVector; +import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.matrixtype.dense.DenseMatrix; +import com.numericalmethod.suanshu.algebra.linear.matrix.doubles.operation.Inverse; +import com.numericalmethod.suanshu.analysis.function.polynomial.Polynomial; +import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRoot; +import com.numericalmethod.suanshu.analysis.function.polynomial.root.PolyRootSolver; +import com.numericalmethod.suanshu.number.complex.Complex; + +class SuanShuMath { + + private static final Logger log = LoggerFactory.getLogger(SuanShuMath.class); + + public static void main(String[] args) throws Exception { + SuanShuMath math = new SuanShuMath(); + + math.addingVectors(); + math.scaleVector(); + math.innerProductVectors(); + math.addingIncorrectVectors(); + + math.addingMatrices(); + math.multiplyMatrices(); + math.multiplyIncorrectMatrices(); + math.inverseMatrix(); + + Polynomial p = math.createPolynomial(); + math.evaluatePolynomial(p); + math.solvePolynomial(); + } + + public void addingVectors() throws Exception { + Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5}); + Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1}); + Vector v3 = v1.add(v2); + log.info("Adding vectors: {}", v3); + } + + public void scaleVector() throws Exception { + Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5}); + Vector v2 = v1.scaled(2.0); + log.info("Scaling a vector: {}", v2); + } + + public void innerProductVectors() throws Exception { + Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5}); + Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1}); + double inner = v1.innerProduct(v2); + log.info("Vector inner product: {}", inner); + } + + public void addingIncorrectVectors() throws Exception { + Vector v1 = new DenseVector(new double[]{1, 2, 3}); + Vector v2 = new DenseVector(new double[]{5, 4}); + Vector v3 = v1.add(v2); + log.info("Adding vectors: {}", v3); + } + + public void addingMatrices() throws Exception { + Matrix m1 = new DenseMatrix(new double[][]{ + {1, 2, 3}, + {4, 5, 6} + }); + + Matrix m2 = new DenseMatrix(new double[][]{ + {3, 2, 1}, + {6, 5, 4} + }); + + Matrix m3 = m1.add(m2); + log.info("Adding matrices: {}", m3); + } + + public void multiplyMatrices() throws Exception { + Matrix m1 = new DenseMatrix(new double[][]{ + {1, 2, 3}, + {4, 5, 6} + }); + + Matrix m2 = new DenseMatrix(new double[][]{ + {1, 4}, + {2, 5}, + {3, 6} + }); + + Matrix m3 = m1.multiply(m2); + log.info("Multiplying matrices: {}", m3); + } + + public void multiplyIncorrectMatrices() throws Exception { + Matrix m1 = new DenseMatrix(new double[][]{ + {1, 2, 3}, + {4, 5, 6} + }); + + Matrix m2 = new DenseMatrix(new double[][]{ + {3, 2, 1}, + {6, 5, 4} + }); + + Matrix m3 = m1.multiply(m2); + log.info("Multiplying matrices: {}", m3); + } + + public void inverseMatrix() { + Matrix m1 = new DenseMatrix(new double[][]{ + {1, 2}, + {3, 4} + }); + + Inverse m2 = new Inverse(m1); + log.info("Inverting a matrix: {}", m2); + log.info("Verifying a matrix inverse: {}", m1.multiply(m2)); + } + + public Polynomial createPolynomial() { + return new Polynomial(new double[]{3, -5, 1}); + } + + public void evaluatePolynomial(Polynomial p) { + // Evaluate using a real number + log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5)); + // Evaluate using a complex number + log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2))); + } + + public void solvePolynomial() { + Polynomial p = new Polynomial(new double[]{2, 2, -4}); + PolyRootSolver solver = new PolyRoot(); + List roots = solver.solve(p); + log.info("Finding polynomial roots: {}", roots); + } + +} From 8c3598b441a3e5f0ba2e3ab887c3d1633ce23638 Mon Sep 17 00:00:00 2001 From: the-java-guy <39062630+the-java-guy@users.noreply.github.com> Date: Thu, 18 Oct 2018 09:41:25 +0530 Subject: [PATCH 28/39] BAEL - 2166 (#5379) * Bean Object, server side and client side example for event streaming example * BAEL-1628 Access a File from the Classpath in a Spring Application * inputstream retrieval added * Removed files related to evaluation article * + Aligning code to the article. Removed Utility methods and classes * Precommit fix * PMD fixes * Code Review changes Refactored : whenResourceUtils_thenReadSuccessful * BAEL-1934 * +indentation correction in pom.xml * synced with master * Precommit : rebase * BAEL-1782 * BAEL - 2166 : Password Generation * Removed unnecessary javaDoc * Segregated utility method --- java-strings/pom.xml | 12 +- .../password/RandomPasswordGenerator.java | 152 ++++++++++++++++++ .../password/StringPasswordUnitTest.java | 64 ++++++++ 3 files changed, 227 insertions(+), 1 deletion(-) create mode 100644 java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java create mode 100644 java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java diff --git a/java-strings/pom.xml b/java-strings/pom.xml index b1ba49b33a..a43490ce5c 100644 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -68,7 +68,17 @@ emoji-java 4.0.0 - + + + org.passay + passay + 1.3.1 + + + org.apache.commons + commons-text + 1.4 + diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java new file mode 100644 index 0000000000..46af4d7c51 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java @@ -0,0 +1,152 @@ +package com.baeldung.string.password; + +import java.security.SecureRandom; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.text.RandomStringGenerator; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +public class RandomPasswordGenerator { + + /** + * Special characters allowed in password. + */ + public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+"; + + public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS"; + + Random random = new SecureRandom(); + + public String generatePassayPassword() { + PasswordGenerator gen = new PasswordGenerator(); + CharacterData lowerCaseChars = EnglishCharacterData.LowerCase; + CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars); + lowerCaseRule.setNumberOfCharacters(2); + CharacterData upperCaseChars = EnglishCharacterData.UpperCase; + CharacterRule upperCaseRule = new CharacterRule(upperCaseChars); + upperCaseRule.setNumberOfCharacters(2); + CharacterData digitChars = EnglishCharacterData.Digit; + CharacterRule digitRule = new CharacterRule(digitChars); + digitRule.setNumberOfCharacters(2); + CharacterData specialChars = new CharacterData() { + public String getErrorCode() { + return ERROR_CODE; + } + + public String getCharacters() { + return ALLOWED_SPL_CHARACTERS; + } + }; + CharacterRule splCharRule = new CharacterRule(specialChars); + splCharRule.setNumberOfCharacters(2); + String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule); + return password; + } + + public String generateCommonTextPassword() { + String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2)) + .concat(generateRandomAlphabet(2, true)) + .concat(generateRandomAlphabet(2, false)) + .concat(generateRandomCharacters(2)); + List pwChars = pwString.chars() + .mapToObj(data -> (char) data) + .collect(Collectors.toList()); + Collections.shuffle(pwChars); + String password = pwChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateCommonsLang3Password() { + String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true); + String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true); + String numbers = RandomStringUtils.randomNumeric(2); + String specialChar = RandomStringUtils.random(2, 33, 47, false, false); + String totalChars = RandomStringUtils.randomAlphanumeric(2); + String combinedChars = upperCaseLetters.concat(lowerCaseLetters) + .concat(numbers) + .concat(specialChar) + .concat(totalChars); + List pwdChars = combinedChars.chars() + .mapToObj(c -> (char) c) + .collect(Collectors.toList()); + Collections.shuffle(pwdChars); + String password = pwdChars.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateSecureRandomPassword() { + Stream pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false)))); + List charList = pwdStream.collect(Collectors.toList()); + Collections.shuffle(charList); + String password = charList.stream() + .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) + .toString(); + return password; + } + + public String generateRandomSpecialCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomNumbers(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomCharacters(int length) { + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57) + .build(); + return pwdGenerator.generate(length); + } + + public String generateRandomAlphabet(int length, boolean lowerCase) { + int low; + int hi; + if (lowerCase) { + low = 97; + hi = 122; + } else { + low = 65; + hi = 90; + } + RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi) + .build(); + return pwdGenerator.generate(length); + } + + public Stream getRandomAlphabets(int count, boolean upperCase) { + IntStream characters = null; + if (upperCase) { + characters = random.ints(count, 65, 90); + } else { + characters = random.ints(count, 97, 122); + } + return characters.mapToObj(data -> (char) data); + } + + public Stream getRandomNumbers(int count) { + IntStream numbers = random.ints(count, 48, 57); + return numbers.mapToObj(data -> (char) data); + } + + public Stream getRandomSpecialChars(int count) { + IntStream specialChars = random.ints(count, 33, 45); + return specialChars.mapToObj(data -> (char) data); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java new file mode 100644 index 0000000000..bfd4b0fe8e --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.string.password; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Examples of passwords conforming to various specifications, using different libraries. + * + */ +public class StringPasswordUnitTest { + + RandomPasswordGenerator passGen = new RandomPasswordGenerator(); + + @Test + public void whenPasswordGeneratedUsingPassay_thenSuccessful() { + String password = passGen.generatePassayPassword(); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue("Password validation failed in Passay", specialCharCount >= 2); + } + + @Test + public void whenPasswordGeneratedUsingCommonsText_thenSuccessful() { + RandomPasswordGenerator passGen = new RandomPasswordGenerator(); + String password = passGen.generateCommonTextPassword(); + int lowerCaseCount = 0; + for (char c : password.toCharArray()) { + if (c >= 97 || c <= 122) { + lowerCaseCount++; + } + } + assertTrue("Password validation failed in commons-text ", lowerCaseCount >= 2); + } + + @Test + public void whenPasswordGeneratedUsingCommonsLang3_thenSuccessful() { + String password = passGen.generateCommonsLang3Password(); + int numCount = 0; + for (char c : password.toCharArray()) { + if (c >= 48 || c <= 57) { + numCount++; + } + } + assertTrue("Password validation failed in commons-lang3", numCount >= 2); + } + + @Test + public void whenPasswordGeneratedUsingSecureRandom_thenSuccessful() { + String password = passGen.generateSecureRandomPassword(); + int specialCharCount = 0; + for (char c : password.toCharArray()) { + if (c >= 33 || c <= 47) { + specialCharCount++; + } + } + assertTrue("Password validation failed in Secure Random", specialCharCount >= 2); + } + +} From a982f70f28391c406e5aadcd96207f4efde98599 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 18 Oct 2018 19:49:28 +0530 Subject: [PATCH 29/39] Update pom.xml --- spring-security-rest/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 70967ce214..ef16f2201b 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -297,5 +297,4 @@ 1.6.1 - From ef3614a5a01812d0db40b1561948f06b2d1dfd17 Mon Sep 17 00:00:00 2001 From: mstefanec <42640465+mstefanec@users.noreply.github.com> Date: Thu, 18 Oct 2018 17:47:27 +0200 Subject: [PATCH 30/39] Programatical sequences in project reactor (#5482) * Added programatically creating sequences in project reactor * Added programatically creating sequences in project reactor --- .../baeldung/reactor/ItemProducerCreate.java | 44 ++++++++++++++ .../reactor/NetworTrafficProducerPush.java | 34 +++++++++++ .../reactor/ProgramaticSequences.java | 58 +++++++++++++++++++ .../baeldung/reactor/StatelessGenerate.java | 24 ++++++++ 4 files changed, 160 insertions(+) create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java create mode 100644 reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java diff --git a/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java b/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java new file mode 100644 index 0000000000..6078f8ef0b --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java @@ -0,0 +1,44 @@ +package com.baeldung.reactor; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; + +public class ItemProducerCreate { + + Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class); + + Consumer> listener; + + public void create() { + Flux articlesFlux = Flux.create((sink) -> { + ItemProducerCreate.this.listener = (items) -> { + items.stream() + .forEach(article -> sink.next(article)); + }; + }); + articlesFlux.subscribe(ItemProducerCreate.this.logger::info); + } + + public static void main(String[] args) { + ItemProducerCreate producer = new ItemProducerCreate(); + producer.create(); + + new Thread(new Runnable() { + + @Override + public void run() { + List items = new ArrayList<>(); + items.add("Item 1"); + items.add("Item 2"); + items.add("Item 3"); + producer.listener.accept(items); + } + }).start(); + } +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java b/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java new file mode 100644 index 0000000000..807ceae84d --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java @@ -0,0 +1,34 @@ +package com.baeldung.reactor; + +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxSink.OverflowStrategy; + +public class NetworTrafficProducerPush { + + Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class); + + Consumer listener; + + public void subscribe(Consumer consumer) { + Flux flux = Flux.push(sink -> { + NetworTrafficProducerPush.this.listener = (t) -> sink.next(t); + }, OverflowStrategy.DROP); + flux.subscribe(consumer); + } + + public void onPacket(String packet) { + listener.accept(packet); + } + + public static void main(String[] args) { + NetworTrafficProducerPush trafficProducer = new NetworTrafficProducerPush(); + trafficProducer.subscribe(trafficProducer.logger::info); + trafficProducer.onPacket("Packet[A18]"); + } + +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java b/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java new file mode 100644 index 0000000000..b52def377d --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java @@ -0,0 +1,58 @@ +package com.baeldung.reactor; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; + +public class ProgramaticSequences { + + Logger logger = LoggerFactory.getLogger(ProgramaticSequences.class); + + public void statefullImutableGenerate() { + Flux flux = Flux.generate(() -> 1, (state, sink) -> { + sink.next("2 + " + state + " = " + 2 + state); + if (state == 101) + sink.complete(); + return state + 1; + }); + + flux.subscribe(logger::info); + } + + public void statefullMutableGenerate() { + Flux flux = Flux.generate(AtomicInteger::new, (state, sink) -> { + int i = state.getAndIncrement(); + sink.next("2 + " + state + " = " + 2 + state); + if (i == 101) + sink.complete(); + return state; + }); + + flux.subscribe(logger::info); + } + + public void handle() { + Flux elephants = Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .handle((i, sink) -> { + String animal = "Elephant nr " + i; + if (i % 2 == 0) { + sink.next(animal); + } + }); + + elephants.subscribe(logger::info); + } + + public static void main(String[] args) { + ProgramaticSequences ps = new ProgramaticSequences(); + + ps.statefullImutableGenerate(); + ps.statefullMutableGenerate(); + ps.handle(); + + } + +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java b/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java new file mode 100644 index 0000000000..c82f8e160b --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java @@ -0,0 +1,24 @@ +package com.baeldung.reactor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; + +public class StatelessGenerate { + + Logger logger = LoggerFactory.getLogger(StatelessGenerate.class); + + public void statelessGenerate() { + Flux flux = Flux.generate((sink) -> { + sink.next("hallo"); + }); + flux.subscribe(logger::info); + } + + public static void main(String[] args) { + StatelessGenerate ps = new StatelessGenerate(); + ps.statelessGenerate(); + } + +} From c1e522d38c9db01136c27efde516471c9be4f280 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 18 Oct 2018 21:26:37 +0530 Subject: [PATCH 31/39] BAEL-9654 Activating multiple profiles for Travis CI (#5483) -Modified travis.yml to execute both default-first and default-second profile --- .travis.yml | 2 +- pom.xml | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5e2d690b4e..683422dc97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ before_install: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc install: skip -script: travis_wait 60 mvn -q install -Pdefault +script: travis_wait 60 mvn -q install -Pdefault-first,default-second sudo: required diff --git a/pom.xml b/pom.xml index beb10b3287..a0c54f4b8a 100644 --- a/pom.xml +++ b/pom.xml @@ -458,7 +458,6 @@ spring-5 spring-5-data-reactive spring-5-reactive - spring-data-5-reactive/spring-5-data-reactive-redis spring-5-reactive-security spring-5-reactive-client spring-5-mvc From cb9ffa4a4ac026386a398f502421bdb03af589a5 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Thu, 18 Oct 2018 21:16:33 +0200 Subject: [PATCH 32/39] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 9e38dfc47d..84c91c5f6e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -156,3 +156,4 @@ - [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [Java Switch Statement](https://www.baeldung.com/java-switch) +- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) From 6fd52ad66c9c6c29cea89f55084e1ed5f7ac6252 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 18 Oct 2018 22:59:29 +0300 Subject: [PATCH 33/39] Update StringToByteArrayUnitTest.java --- .../com/baeldung/java8/base64/StringToByteArrayUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java index 5bb97e111a..c5f7051c25 100644 --- a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java @@ -56,5 +56,4 @@ public class StringToByteArrayUnitTest { assertEquals("test input", new String(result)); } - } From 8caaf775568fee31ae5ad0b9e511b79d8bb30cc7 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Thu, 18 Oct 2018 21:55:28 -0500 Subject: [PATCH 34/39] BAEL-2200 and BAEL-2287 README updates (#5487) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * BAEL-2026 add link back to article * BAEL-2029: add link back to article * BAEL-1898: Add link back to article * BAEL-2102 and BAEL-2131 Add links back to articles * BAEL-2132 Add link back to article * BAEL-1980: add link back to article * BAEL-2200: Display auto-configuration report in Spring Boot * BAEL-2253: Add link back to article * BAEL-2200 BAEL-2287 Add links back to articles --- core-java-collections/README.md | 1 + spring-boot/README.MD | 1 + 2 files changed, 2 insertions(+) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index aef640634e..e366232f74 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -55,3 +55,4 @@ - [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) - [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) +- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 192c4f9fed..aed2d2c5f8 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -34,3 +34,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) From 361448cc396f2508cca8b66e80f25f549ee8bde9 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 19 Oct 2018 12:23:39 +0530 Subject: [PATCH 35/39] [BAEL-9547] - Moved 3 articles from guava to guava-collections --- guava-collections/README.md | 5 ++++- .../java/org/baeldung/guava/ClassToInstanceMapUnitTest.java | 0 .../src/test/java/org/baeldung/guava/GuavaTableUnitTest.java | 0 guava/README.md | 3 --- 4 files changed, 4 insertions(+), 4 deletions(-) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/ClassToInstanceMapUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaTableUnitTest.java (100%) diff --git a/guava-collections/README.md b/guava-collections/README.md index eb1eb1d35c..fc9cf549c3 100644 --- a/guava-collections/README.md +++ b/guava-collections/README.md @@ -17,4 +17,7 @@ - [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) - [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) - [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) \ No newline at end of file +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) +- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) +- [Guide to Guava Table](http://www.baeldung.com/guava-table) +- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/ClassToInstanceMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/ClassToInstanceMapUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/ClassToInstanceMapUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/ClassToInstanceMapUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaTableUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaTableUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaTableUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaTableUnitTest.java diff --git a/guava/README.md b/guava/README.md index 7501bf08de..56e6aff50c 100644 --- a/guava/README.md +++ b/guava/README.md @@ -6,15 +6,12 @@ ### Relevant Articles: - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) -- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) - [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering) - [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions) - [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader) - [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer) - [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus) -- [Guide to Guava Table](http://www.baeldung.com/guava-table) - [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection) -- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) From e2d1f25dc57c34efaf6929e7d933bfa3b482888e Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 19 Oct 2018 19:37:21 +0530 Subject: [PATCH 36/39] BAEL-9467 Update Spring Security article - Upgraded xml schema versions to latest --- spring-security-rest/src/main/resources/webSecurityConfig.xml | 4 ++-- spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-security-rest/src/main/resources/webSecurityConfig.xml b/spring-security-rest/src/main/resources/webSecurityConfig.xml index 54bd0f91b9..edd3cba39c 100644 --- a/spring-security-rest/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest/src/main/resources/webSecurityConfig.xml @@ -5,9 +5,9 @@ xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-4.2.xsd + http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> + http://www.springframework.org/schema/beans/spring-beans.xsd">