diff --git a/core-groovy/README.md b/core-groovy/README.md index 71788acdb779..ec2fcfa574c1 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -4,3 +4,7 @@ - [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy) - [Working with JSON in Groovy](http://www.baeldung.com/groovy-json) +- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) +- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) +- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) +- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index e54c7662803a..029e5460abdd 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -23,6 +23,12 @@ org.codehaus.groovy groovy-all ${groovy-all.version} + pom + + + org.codehaus.groovy + groovy-dateutil + ${groovy.version} org.codehaus.groovy @@ -103,9 +109,12 @@ 1.0.0 - 2.4.13 - 2.4.13 - 2.4.13 + + + + 2.5.6 + 2.5.6 + 2.5.6 2.4.0 1.1-groovy-2.4 1.6 diff --git a/core-groovy/src/test/groovy/com/baeldung/date/DateTest.groovy b/core-groovy/src/test/groovy/com/baeldung/date/DateTest.groovy new file mode 100644 index 000000000000..4e7a7189a62f --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/date/DateTest.groovy @@ -0,0 +1,57 @@ +package com.baeldung.groovy.sql + +import static org.junit.Assert.* +import java.util.Calendar.* +import java.time.LocalDate +import java.text.SimpleDateFormat +import org.junit.Test + + +class DateTest { + + def dateStr = "2019-02-28" + def pattern = "yyyy-MM-dd" + + @Test + void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() { + def dateFormat = new SimpleDateFormat(pattern) + def date = dateFormat.parse(dateStr) + + println(" String to Date with DateFormatter : " + date) + + def cal = new GregorianCalendar(); + cal.setTime(date); + + assertEquals(cal.get(Calendar.YEAR),2019) + assertEquals(cal.get(Calendar.DAY_OF_MONTH),28) + assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY) + } + + @Test + void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() { + + def date = Date.parse(pattern, dateStr) + + println(" String to Date with Date.parse : " + date) + + def cal = new GregorianCalendar(); + cal.setTime(date); + + assertEquals(cal.get(Calendar.YEAR),2019) + assertEquals(cal.get(Calendar.DAY_OF_MONTH),28) + assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY) + } + + @Test + void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() { + def date = LocalDate.parse(dateStr, pattern) + + println(" String to Date with LocalDate : " + date) + + assertEquals(date.getYear(),2019) + assertEquals(date.getMonth(),java.time.Month.FEBRUARY) + assertEquals(date.getDayOfMonth(),28) + } + + +} diff --git a/core-java-8/README.md b/core-java-8/README.md index f601ea9d378c..6b5b79470e63 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -38,3 +38,4 @@ - [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs) - [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) +- [Method References in Java](https://www.baeldung.com/java-method-references) diff --git a/core-java-9/README.md b/core-java-9/README.md index 904782819c65..224306db1924 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -27,3 +27,5 @@ - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) +- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) +- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md index 5fe84480db80..c5139074e974 100644 --- a/core-java-collections-list/README.md +++ b/core-java-collections-list/README.md @@ -28,3 +28,5 @@ - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) +- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) +- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 710be31a0890..80d4385c4574 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -32,3 +32,4 @@ - [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) +- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) diff --git a/core-java-collections/src/main/java/com/baeldung/java/sort/CollectionsSortCompare.java b/core-java-collections/src/main/java/com/baeldung/java/sort/CollectionsSortCompare.java new file mode 100644 index 000000000000..1eff522877d4 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/sort/CollectionsSortCompare.java @@ -0,0 +1,39 @@ +package com.baeldung.java.sort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class CollectionsSortCompare { + + public static void main(String[] args) { + sortPrimitives(); + sortReferenceType(); + sortCollection(); + } + + private static void sortReferenceType() { + Integer[] numbers = {5, 22, 10, 0}; + Arrays.sort(numbers); + System.out.println(Arrays.toString(numbers)); + } + + private static void sortCollection() { + List numbersList = new ArrayList<>(); + numbersList.add(5); + numbersList.add(22); + numbersList.add(10); + numbersList.add(0); + + Collections.sort(numbersList); + + numbersList.forEach(System.out::print); + } + + private static void sortPrimitives() { + int[] numbers = {5, 22, 10, 0}; + Arrays.sort(numbers); + System.out.println(Arrays.toString(numbers)); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java new file mode 100644 index 000000000000..a1d40657d306 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArraySortBenchmark.java @@ -0,0 +1,47 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 100000, iterations = 10) +@Warmup(batchSize = 100000, iterations = 10) +public class ArraySortBenchmark { + + @State(Scope.Thread) + public static class Initialize { + Integer[] numbers = {5, 22, 10, 0}; + int[] primitives = {5, 22, 10, 0}; + } + + @Benchmark + public Integer[] benchmarkArraysIntegerSort(ArraySortBenchmark.Initialize state) { + Arrays.sort(state.numbers); + return state.numbers; + } + + @Benchmark + public int[] benchmarkArraysIntSort(ArraySortBenchmark.Initialize state) { + Arrays.sort(state.primitives); + return state.primitives; + } + + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ArraySortBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-lang-oop/README.md b/core-java-lang-oop/README.md index bbc3d26c9904..200415fe21d1 100644 --- a/core-java-lang-oop/README.md +++ b/core-java-lang-oop/README.md @@ -22,3 +22,4 @@ - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) - [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) +- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces) diff --git a/core-java-lang/README.md b/core-java-lang/README.md index c1c22caf6c5b..eaedc93eeddb 100644 --- a/core-java-lang/README.md +++ b/core-java-lang/README.md @@ -41,3 +41,4 @@ - [Java Interfaces](https://www.baeldung.com/java-interfaces) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) +- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index f6ce44d72f3c..e76f28030da1 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -14,3 +14,4 @@ - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding) - [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) +- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index d2fd903c106f..67538a389531 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -19,7 +19,6 @@ - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) -- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) @@ -51,3 +50,4 @@ - [Using Curl in Java](https://www.baeldung.com/java-curl) - [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year) - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) +- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) diff --git a/core-java/src/main/java/com/baeldung/urlconnection/PostJSONWithHttpURLConnection.java b/core-java/src/main/java/com/baeldung/urlconnection/PostJSONWithHttpURLConnection.java new file mode 100644 index 000000000000..38b4a0411d7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/urlconnection/PostJSONWithHttpURLConnection.java @@ -0,0 +1,46 @@ +package com.baeldung.urlconnection; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +public class PostJSONWithHttpURLConnection { + + public static void main (String []args) throws IOException{ + //Change the URL with any other publicly accessible POST resource, which accepts JSON request body + URL url = new URL ("https://reqres.in/api/users"); + + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setRequestMethod("POST"); + + con.setRequestProperty("Content-Type", "application/json; utf-8"); + con.setRequestProperty("Accept", "application/json"); + + con.setDoOutput(true); + + //JSON String need to be constructed for the specific resource. + //We may construct complex JSON using any third-party JSON libraries such as jackson or org.json + String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}"; + + try(OutputStream os = con.getOutputStream()){ + byte[] input = jsonInputString.getBytes("utf-8"); + os.write(input, 0, input.length); + } + + int code = con.getResponseCode(); + System.out.println(code); + + try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){ + StringBuilder response = new StringBuilder(); + String responseLine = null; + while ((responseLine = br.readLine()) != null) { + response.append(responseLine.trim()); + } + System.out.println(response.toString()); + } + } + +} diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index 6aabd71a6cda..8d22c4f1a85f 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) +- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) diff --git a/core-kotlin-2/src/test/kotlin/stringcomparison/StringComparisonTest.kt b/core-kotlin-2/src/test/kotlin/stringcomparison/StringComparisonTest.kt new file mode 100644 index 000000000000..45a8dd7e04d9 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/stringcomparison/StringComparisonTest.kt @@ -0,0 +1,47 @@ +package stringcomparison + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class StringComparisonUnitTest { + + @Test + fun `compare using equals operator`() { + val first = "kotlin" + val second = "kotlin" + val firstCapitalized = "KOTLIN" + assertTrue { first == second } + assertFalse { first == firstCapitalized } + } + + @Test + fun `compare using referential equals operator`() { + val first = "kotlin" + val second = "kotlin" + val copyOfFirst = buildString { "kotlin" } + assertTrue { first === second } + assertFalse { first === copyOfFirst } + } + + @Test + fun `compare using equals method`() { + val first = "kotlin" + val second = "kotlin" + val firstCapitalized = "KOTLIN" + assertTrue { first.equals(second) } + assertFalse { first.equals(firstCapitalized) } + assertTrue { first.equals(firstCapitalized, true) } + } + + @Test + fun `compare using compare method`() { + val first = "kotlin" + val second = "kotlin" + val firstCapitalized = "KOTLIN" + assertTrue { first.compareTo(second) == 0 } + assertTrue { first.compareTo(firstCapitalized) == 32 } + assertTrue { firstCapitalized.compareTo(first) == -32 } + assertTrue { first.compareTo(firstCapitalized, true) == 0 } + } +} \ No newline at end of file diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 45163b3f99d6..7d8001d66747 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -52,3 +52,5 @@ - [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) - [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) - [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) +- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) +- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) diff --git a/geotools/pom.xml b/geotools/pom.xml index f2a9a77d2a58..17beded326de 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -33,24 +33,11 @@ - - maven2-repository.dev.java.net - Java.net repository - http://download.java.net/maven/2 - osgeo Open Source Geospatial Foundation Repository http://download.osgeo.org/webdav/geotools/ - - - true - - opengeo - OpenGeo Maven Repository - http://repo.opengeo.org - diff --git a/gson/README.md b/gson/README.md index 4edd7158d4ff..02b06eac20d4 100644 --- a/gson/README.md +++ b/gson/README.md @@ -10,3 +10,4 @@ - [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file) - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) - [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) +- [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject) diff --git a/guice/README.md b/guice/README.md index d1bd1ff8833c..77c788c36374 100644 --- a/guice/README.md +++ b/guice/README.md @@ -2,3 +2,4 @@ ### Relevant Articles - [Guide to Google Guice](http://www.baeldung.com/guice) +- [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md index 5d65e961de06..2eeb2c884319 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -20,3 +20,4 @@ - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) +- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) diff --git a/java-streams/src/main/java/com/baeldung/reduce/application/Application.java b/java-streams/src/main/java/com/baeldung/reduce/application/Application.java new file mode 100644 index 000000000000..b101c86780c9 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/reduce/application/Application.java @@ -0,0 +1,70 @@ +package com.baeldung.reduce.application; + +import com.baeldung.reduce.entities.User; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Warmup; + +public class Application { + + public static void main(String[] args) throws Exception { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + System.out.println(result1); + + int result2 = numbers.stream().reduce(0, Integer::sum); + System.out.println(result2); + + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); + System.out.println(result3); + + String result4 = letters.stream().reduce("", String::concat); + System.out.println(result4); + + String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + System.out.println(result5); + + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result6); + + String result7 = letters.parallelStream().reduce("", String::concat); + System.out.println(result7); + + int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result8); + + org.openjdk.jmh.Main.main(args); + + } + + @Benchmark + @Fork(value = 1, warmups = 2) + @Warmup(iterations = 2) + @BenchmarkMode(Mode.AverageTime) + public void executeReduceOnParallelizedStream() { + List userList = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + userList.add(new User("John" + i, i)); + } + userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } + + @Benchmark + @Fork(value = 1, warmups = 2) + @Warmup(iterations = 2) + @BenchmarkMode(Mode.AverageTime) + public void executeReduceOnSequentialStream() { + List userList = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + userList.add(new User("John" + i, i)); + } + userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } +} diff --git a/java-streams/src/main/java/com/baeldung/reduce/entities/User.java b/java-streams/src/main/java/com/baeldung/reduce/entities/User.java new file mode 100644 index 000000000000..a17c6a02b6e7 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/reduce/entities/User.java @@ -0,0 +1,25 @@ +package com.baeldung.reduce.entities; + +public class User { + + private final String name; + private final int age; + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", age=" + age + '}'; + } +} diff --git a/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java new file mode 100644 index 000000000000..8b4af2cbe2ab --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java @@ -0,0 +1,52 @@ +package com.baeldung.reduce.utilities; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class NumberUtils { + + private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); + + public static int divideListElements(List values, Integer divider) { + return values.stream() + .reduce(0, (a, b) -> { + try { + return a / divider + b / divider; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return 0; + }); + } + + public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { + return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); + } + + public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { + BiFunction division = (a, b) -> a / b; + return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); + } + + private static int divide(int value, int factor) { + int result = 0; + try { + result = value / factor; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return result; + } + + private static int applyFunction(BiFunction function, int a, int b) { + try { + return function.apply(a, b); + } + catch(Exception e) { + LOGGER.log(Level.INFO, "Exception occurred!"); + } + return 0; + } +} diff --git a/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java new file mode 100644 index 000000000000..8e2ff7bf2256 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.reduce.tests; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class StreamReduceUnitTest { + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, (a, b) -> a + b); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, Integer::sum); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (a, b) -> a + b); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); + assertThat(result).isEqualTo("ABCDE"); + } + + @Test + public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + assertThat(result).isEqualTo(65); + } + + @Test + public void givenStringList_whenReduceWithParallelStream_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.parallelStream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); + } +} diff --git a/java-strings/README.md b/java-strings/README.md index fc9748cd2c4e..b342f5391817 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -53,3 +53,4 @@ - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) - [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) diff --git a/jhipster/README.md b/jhipster/README.md index 91ba54bf6089..289bfac75441 100644 --- a/jhipster/README.md +++ b/jhipster/README.md @@ -3,3 +3,4 @@ - [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) - [Intro to JHipster](http://www.baeldung.com/jhipster) - [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) +- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles) diff --git a/jhipster/jhipster-uaa/pom.xml b/jhipster/jhipster-uaa/pom.xml index 88df59b735c1..a59b19d1fdea 100644 --- a/jhipster/jhipster-uaa/pom.xml +++ b/jhipster/jhipster-uaa/pom.xml @@ -2,9 +2,8 @@ 4.0.0 - com.baeldung.jhipster - jhipster-microservice-uaa - JHipster Microservice with UAA + jhipster-uaa + jhipster-uaa pom diff --git a/json/README.md b/json/README.md index 2e253a4ae900..c0ca4b00efac 100644 --- a/json/README.md +++ b/json/README.md @@ -11,3 +11,5 @@ - [Overview of JSON Pointer](https://www.baeldung.com/json-pointer) - [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api) - [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key) +- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) +- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) diff --git a/libraries/README.md b/libraries/README.md index 378317778e68..57f22631f1d9 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -66,6 +66,7 @@ - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) - [Intro to Derive4J](https://www.baeldung.com/derive4j) +- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/lombok-custom/pom.xml b/lombok-custom/pom.xml index f016405fd664..cfbe62994579 100644 --- a/lombok-custom/pom.xml +++ b/lombok-custom/pom.xml @@ -5,6 +5,7 @@ 4.0.0 lombok-custom + lombok-custom 0.1-SNAPSHOT diff --git a/maven/README.md b/maven/README.md index 1c0e50f95a24..1352a2a10f1b 100644 --- a/maven/README.md +++ b/maven/README.md @@ -14,3 +14,4 @@ - [Apache Maven Tutorial](https://www.baeldung.com/maven) - [Use the Latest Version of a Dependency in Maven](https://www.baeldung.com/maven-dependency-latest-version) - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) +- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) diff --git a/maven/custom-rule/pom.xml b/maven/custom-rule/pom.xml index f76e0db11e24..25a3489fb9d0 100644 --- a/maven/custom-rule/pom.xml +++ b/maven/custom-rule/pom.xml @@ -9,6 +9,7 @@ 4.0.0 custom-rule + custom-rule 3.0.0-M2 diff --git a/maven/maven-enforcer/pom.xml b/maven/maven-enforcer/pom.xml index d54471e66ca6..9826beb0d9e0 100644 --- a/maven/maven-enforcer/pom.xml +++ b/maven/maven-enforcer/pom.xml @@ -9,6 +9,7 @@ 4.0.0 maven-enforcer + maven-enforcer diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml index 95ac1fc0fb61..2bc1c20eedff 100644 --- a/osgi/osgi-intro-sample-activator/pom.xml +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -3,6 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 osgi-intro-sample-activator + osgi-intro-sample-activator bundle diff --git a/osgi/osgi-intro-sample-client/pom.xml b/osgi/osgi-intro-sample-client/pom.xml index 7f5faedb30ee..a630625ed21b 100644 --- a/osgi/osgi-intro-sample-client/pom.xml +++ b/osgi/osgi-intro-sample-client/pom.xml @@ -5,6 +5,7 @@ 4.0.0 osgi-intro-sample-client + osgi-intro-sample-client bundle diff --git a/osgi/osgi-intro-sample-service/pom.xml b/osgi/osgi-intro-sample-service/pom.xml index 8f81645ad458..4f0b108837aa 100644 --- a/osgi/osgi-intro-sample-service/pom.xml +++ b/osgi/osgi-intro-sample-service/pom.xml @@ -3,6 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 osgi-intro-sample-service + osgi-intro-sample-service bundle diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index 53f91f975d54..1054038623d8 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -55,7 +55,7 @@ 3.1.0 - 1.5.16.RELEASE + 1.5.19.RELEASE diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 280d226e95fe..4b81e27333e4 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -77,9 +77,7 @@ 3.1.0 - 1.0.11.RELEASE - 2.1.1.RELEASE + 1.0.21.RELEASE + 2.1.3.RELEASE - - diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 8046d2034b3e..a4513b7d95f1 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -18,3 +18,4 @@ - [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern) - [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) +- [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) diff --git a/patterns/solid/pom.xml b/patterns/solid/pom.xml index 283750419797..146a9903cff8 100644 --- a/patterns/solid/pom.xml +++ b/patterns/solid/pom.xml @@ -5,6 +5,7 @@ 4.0.0 com.baeldung solid + solid 1.0-SNAPSHOT diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index b7f2cd838793..a37720a42859 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -30,3 +30,5 @@ - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) - [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) +- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) +- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index 739031ff5e27..9512ad336d7b 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -20,6 +20,8 @@ - [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) - [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) +- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) +- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java index ba077ccf1fde..4299f9e3bb1b 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/CustomItemRepository.java @@ -1,5 +1,7 @@ package com.baeldung.dao.repositories; +import java.util.List; + import org.springframework.stereotype.Repository; import com.baeldung.domain.Item; @@ -12,4 +14,8 @@ public interface CustomItemRepository { Item findItemById(Long id); void findThenDelete(Long id); + + List findItemsByColorAndGrade(); + + List findItemByColorOrGrade(); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java index 53def88af010..9791cb0aa700 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryImpl.java @@ -1,12 +1,18 @@ package com.baeldung.dao.repositories.impl; +import java.util.List; + import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; -import com.baeldung.domain.Item; import com.baeldung.dao.repositories.CustomItemRepository; +import com.baeldung.domain.Item; @Repository public class CustomItemRepositoryImpl implements CustomItemRepository { @@ -29,4 +35,54 @@ public void findThenDelete(Long id) { final Item item = entityManager.find(Item.class, id); entityManager.remove(item); } + + @Override + public List findItemsByColorAndGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor); + + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } + + @Override + public List findItemByColorOrGrade() { + + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Item.class); + Root itemRoot = criteriaQuery.from(Item.class); + + Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red"); + Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D"); + Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA); + + Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue"); + Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B"); + Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB); + + // final search filter + Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB); + + criteriaQuery.where(finalPredicate); + + List items = entityManager.createQuery(criteriaQuery) + .getResultList(); + return items; + } } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java new file mode 100644 index 000000000000..c5fb7fa25ff0 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/impl/CustomItemRepositoryIntegrationTest.java @@ -0,0 +1,94 @@ +package com.baeldung.dao.repositories.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.CollectionUtils; + +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; +import com.baeldung.dao.repositories.CustomItemRepository; +import com.baeldung.domain.Item; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class }) +public class CustomItemRepositoryIntegrationTest { + + @Autowired + CustomItemRepository customItemRepositoryImpl; + + @Autowired + EntityManager entityManager; + + @Before + public void setUp() { + + Item firstItem = new Item(); + firstItem.setColor("blue"); + firstItem.setGrade("C"); + firstItem.setId(10l); + + entityManager.persist(firstItem); + + Item secondItem = new Item(); + secondItem.setColor("red"); + secondItem.setGrade("C"); + secondItem.setId(11l); + + entityManager.persist(secondItem); + + Item thirdItem = new Item(); + thirdItem.setColor("blue"); + thirdItem.setGrade("A"); + thirdItem.setId(12l); + + entityManager.persist(thirdItem); + + Item fourthItem = new Item(); + fourthItem.setColor("red"); + fourthItem.setGrade("D"); + fourthItem.setId(13l); + + entityManager.persist(fourthItem); + } + + @Test + public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() { + + List items = customItemRepositoryImpl.findItemsByColorAndGrade(); + + assertFalse("No items found", CollectionUtils.isEmpty(items)); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have blue color", "blue", item.getColor()); + assertEquals("this item does not belong to A grade", "A", item.getGrade()); + } + + @Test + public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() { + + List items = customItemRepositoryImpl.findItemByColorOrGrade(); + + assertFalse("No items found", CollectionUtils.isEmpty(items)); + assertEquals("There should be only one item", 1, items.size()); + + Item item = items.get(0); + + assertEquals("this item do not have red color", "red", item.getColor()); + assertEquals("this item does not belong to D grade", "D", item.getGrade()); + } + +} diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 23c03d3bef81..2f2a27e4ace4 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -15,7 +15,6 @@ - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) - [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) -- [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) diff --git a/pom.xml b/pom.xml index ac302534c0b5..0a401299bad1 100644 --- a/pom.xml +++ b/pom.xml @@ -412,7 +412,7 @@ feign flyway-cdi-extension - + geotools google-cloud google-web-toolkit @@ -542,7 +542,7 @@ persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink - + persistence-modules/spring-data-elasticsearch persistence-modules/spring-data-gemfire persistence-modules/spring-data-jpa persistence-modules/spring-data-keyvalue @@ -1130,7 +1130,7 @@ feign flyway-cdi-extension - + geotools google-cloud google-web-toolkit @@ -1260,7 +1260,7 @@ persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink - + persistence-modules/spring-data-elasticsearch persistence-modules/spring-data-gemfire persistence-modules/spring-data-jpa persistence-modules/spring-data-keyvalue diff --git a/ratpack/README.md b/ratpack/README.md index dded42fab6dc..14bc3f6c74de 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -5,3 +5,4 @@ - [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) +- [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava) diff --git a/restx/pom.xml b/restx/pom.xml index 49c06503264c..10c843a20889 100644 --- a/restx/pom.xml +++ b/restx/pom.xml @@ -5,7 +5,7 @@ 4.0.0 restx 0.1-SNAPSHOT - restx-demo + restx war diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index 2519516f45b9..47d16ec8dded 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 rxjava-2 + rxjava-2 1.0-SNAPSHOT diff --git a/software-security/sql-injection-samples/README.md b/software-security/sql-injection-samples/README.md new file mode 100644 index 000000000000..7a077074acf3 --- /dev/null +++ b/software-security/sql-injection-samples/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [SQL Injection and How to Prevent It?](https://www.baeldung.com/sql-injection) diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml index f2ed6d771853..6ea98eb3d0d2 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -2,7 +2,8 @@ 4.0.0 com.baeldung.springbootangular - springbootangular + spring-boot-angular + spring-boot-angular 1.0 jar diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index f13801f5329d..70ebb225c8f1 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -84,7 +84,7 @@ openshift 0.3.0.RELEASE - Finchley.SR2 + Greenwich.RELEASE 3.5.37 @@ -166,7 +166,7 @@ org.springframework.cloud spring-cloud-dependencies - Finchley.SR1 + Greenwich.RELEASE pom import @@ -214,7 +214,7 @@ org.springframework.cloud spring-cloud-dependencies - Finchley.SR1 + Greenwich.RELEASE pom import diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java index 567e9b26783c..d5a597e48b2e 100644 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java @@ -4,12 +4,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.servlet.ServletComponentScan; -import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @ServletComponentScan -@SpringBootApplication -@ComponentScan("com.baeldung") +@SpringBootApplication(scanBasePackages = "com.baeldung") @EnableJpaRepositories("com.baeldung.persistence.repo") @EntityScan("com.baeldung.persistence.model") public class Application { diff --git a/spring-boot-bootstrap/src/main/resources/templates/error.html b/spring-boot-bootstrap/src/main/resources/templates/error.html index f2b51a193850..ca3a740b71cf 100644 --- a/spring-boot-bootstrap/src/main/resources/templates/error.html +++ b/spring-boot-bootstrap/src/main/resources/templates/error.html @@ -1,19 +1,19 @@ - + Error Occurred
-

Error Occurred!

-
- \ No newline at end of file + diff --git a/spring-boot-bootstrap/src/main/resources/templates/home.html b/spring-boot-bootstrap/src/main/resources/templates/home.html index 5707cfb82ab0..0428ca1127c5 100644 --- a/spring-boot-bootstrap/src/main/resources/templates/home.html +++ b/spring-boot-bootstrap/src/main/resources/templates/home.html @@ -1,7 +1,7 @@ - + Home Page

Hello !

Welcome to Our App

- \ No newline at end of file + diff --git a/spring-boot-libraries/README.MD b/spring-boot-libraries/README.MD index cc32ce835598..f3706e0fa4ec 100644 --- a/spring-boot-libraries/README.MD +++ b/spring-boot-libraries/README.MD @@ -4,3 +4,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) +- [A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index 0e1ac5a8ce50..d5a39cdc9f84 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -11,3 +11,4 @@ - [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) +- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index a0adc5a51fbd..8fbc9527b826 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -9,3 +9,4 @@ Module for the articles that are part of the Spring REST E-book: 7. [Versioning a REST API](http://www.baeldung.com/rest-versioning) 8. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) 9. [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) +10. [Testing REST with multiple MIME types](http://www.baeldung.com/testing-rest-api-with-multiple-media-types) diff --git a/spring-boot-rest/src/test/java/com/baeldung/test/TestMarshallerFactory.java b/spring-boot-rest/src/test/java/com/baeldung/test/TestMarshallerFactory.java index 740ee078391a..1a3bae7c8770 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/test/TestMarshallerFactory.java +++ b/spring-boot-rest/src/test/java/com/baeldung/test/TestMarshallerFactory.java @@ -27,8 +27,7 @@ public IMarshaller getObject() { case "json": return new JacksonMarshaller(); case "xml": - // If we need to implement xml marshaller we can include spring-rest-full XStreamMarshaller - throw new IllegalStateException(); + return new XStreamMarshaller(); default: throw new IllegalStateException(); } diff --git a/spring-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java b/spring-boot-rest/src/test/java/com/baeldung/test/XStreamMarshaller.java similarity index 94% rename from spring-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java rename to spring-boot-rest/src/test/java/com/baeldung/test/XStreamMarshaller.java index d7cf084e34dd..957b35218eb3 100644 --- a/spring-rest-full/src/test/java/org/baeldung/test/XStreamMarshaller.java +++ b/spring-boot-rest/src/test/java/com/baeldung/test/XStreamMarshaller.java @@ -1,8 +1,8 @@ -package org.baeldung.test; +package com.baeldung.test; import java.util.List; -import org.baeldung.persistence.model.Foo; +import com.baeldung.persistence.model.Foo; import org.springframework.http.MediaType; import com.google.common.base.Preconditions; diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml index c8b609fd7072..456caf480cbd 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -60,22 +60,11 @@ - - - spring-milestones - Spring Milestones - http://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 1.8 - Greenwich.M3 + Greenwich.RELEASE
diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml index 5b2eb05fc8dd..b7376f7bd468 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -52,22 +52,11 @@ - - - spring-milestones - Spring Milestones - http://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 1.8 - Greenwich.M3 + Greenwich.RELEASE diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml index b87f807391d4..012a81bd8d21 100644 --- a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 liveness-example + liveness-example 1.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml index 42fa10934b84..2b2e57a19c8a 100644 --- a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 readiness-example + readiness-example 1.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml new file mode 100644 index 000000000000..002a33374903 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung.cloud + openfeign + 0.0.1-SNAPSHOT + openfeign + OpenFeign project for Spring Boot + + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + 2.0.1.RELEASE + Finchley.SR2 + + + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + io.github.openfeign + feign-okhttp + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java new file mode 100644 index 000000000000..c7f07f66673a --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.cloud.openfeign; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@SpringBootApplication +@EnableFeignClients +public class ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(ExampleApplication.class, args); + } + +} + diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/JSONPlaceHolderClient.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/JSONPlaceHolderClient.java new file mode 100644 index 000000000000..bdbe6efeeba2 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/JSONPlaceHolderClient.java @@ -0,0 +1,25 @@ +package com.baeldung.cloud.openfeign.client; + +import com.baeldung.cloud.openfeign.config.ClientConfiguration; +import com.baeldung.cloud.openfeign.hystrix.JSONPlaceHolderFallback; +import com.baeldung.cloud.openfeign.model.Post; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import java.util.List; + +@FeignClient(value = "jplaceholder", + url = "https://jsonplaceholder.typicode.com/", + configuration = ClientConfiguration.class, + fallback = JSONPlaceHolderFallback.class) +public interface JSONPlaceHolderClient { + + @RequestMapping(method = RequestMethod.GET, value = "/posts") + List getPosts(); + + + @RequestMapping(method = RequestMethod.GET, value = "/posts/{postId}", produces = "application/json") + Post getPostById(@PathVariable("postId") Long postId); +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/ClientConfiguration.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/ClientConfiguration.java new file mode 100644 index 000000000000..0b16134e92e2 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/ClientConfiguration.java @@ -0,0 +1,37 @@ +package com.baeldung.cloud.openfeign.config; + +import feign.Logger; +import feign.RequestInterceptor; +import feign.codec.ErrorDecoder; +import feign.okhttp.OkHttpClient; +import org.apache.http.entity.ContentType; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ClientConfiguration { + + @Bean + public Logger.Level feignLoggerLevel() { + return Logger.Level.FULL; + } + + @Bean + public ErrorDecoder errorDecoder() { + return new ErrorDecoder.Default(); + } + + @Bean + public OkHttpClient client() { + return new OkHttpClient(); + } + + @Bean + public RequestInterceptor requestInterceptor() { + return requestTemplate -> { + requestTemplate.header("user", "ajeje"); + requestTemplate.header("password", "brazof"); + requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType()); + }; + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/CustomErrorDecoder.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/CustomErrorDecoder.java new file mode 100644 index 000000000000..4d32cf083fa1 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/CustomErrorDecoder.java @@ -0,0 +1,21 @@ +package com.baeldung.cloud.openfeign.config; + +import com.baeldung.cloud.openfeign.exception.BadRequestException; +import com.baeldung.cloud.openfeign.exception.NotFoundException; +import feign.Response; +import feign.codec.ErrorDecoder; + +public class CustomErrorDecoder implements ErrorDecoder { + @Override + public Exception decode(String methodKey, Response response) { + + switch (response.status()){ + case 400: + return new BadRequestException(); + case 404: + return new NotFoundException(); + default: + return new Exception("Generic error"); + } + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java new file mode 100644 index 000000000000..50200957addc --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java @@ -0,0 +1,21 @@ +package com.baeldung.cloud.openfeign.exception; + +public class BadRequestException extends Exception { + + public BadRequestException() { + } + + public BadRequestException(String message) { + super(message); + } + + public BadRequestException(Throwable cause) { + super(cause); + } + + @Override + public String toString() { + return "BadRequestException: "+getMessage(); + } + +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java new file mode 100644 index 000000000000..28d0e95e9a6f --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java @@ -0,0 +1,21 @@ +package com.baeldung.cloud.openfeign.exception; + +public class NotFoundException extends Exception { + + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + @Override + public String toString() { + return "NotFoundException: "+getMessage(); + } + +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/hystrix/JSONPlaceHolderFallback.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/hystrix/JSONPlaceHolderFallback.java new file mode 100644 index 000000000000..1aa311232047 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/hystrix/JSONPlaceHolderFallback.java @@ -0,0 +1,22 @@ +package com.baeldung.cloud.openfeign.hystrix; + +import com.baeldung.cloud.openfeign.client.JSONPlaceHolderClient; +import com.baeldung.cloud.openfeign.model.Post; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.List; + +@Component +public class JSONPlaceHolderFallback implements JSONPlaceHolderClient { + + @Override + public List getPosts() { + return Collections.emptyList(); + } + + @Override + public Post getPostById(Long postId) { + return null; + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Post.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Post.java new file mode 100644 index 000000000000..cab962965357 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Post.java @@ -0,0 +1,41 @@ +package com.baeldung.cloud.openfeign.model; + +public class Post { + + private String userId; + private Long id; + private String title; + private String body; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/JSONPlaceHolderService.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/JSONPlaceHolderService.java new file mode 100644 index 000000000000..16e9b1dbde67 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/JSONPlaceHolderService.java @@ -0,0 +1,12 @@ +package com.baeldung.cloud.openfeign.service; + +import com.baeldung.cloud.openfeign.model.Post; + +import java.util.List; + +public interface JSONPlaceHolderService { + + List getPosts(); + + Post getPostById(Long id); +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/impl/JSONPlaceHolderServiceImpl.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/impl/JSONPlaceHolderServiceImpl.java new file mode 100644 index 000000000000..30348db3c271 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/service/impl/JSONPlaceHolderServiceImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.cloud.openfeign.service.impl; + +import com.baeldung.cloud.openfeign.client.JSONPlaceHolderClient; +import com.baeldung.cloud.openfeign.model.Post; +import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class JSONPlaceHolderServiceImpl implements JSONPlaceHolderService { + + @Autowired + private JSONPlaceHolderClient jsonPlaceHolderClient; + + @Override + public List getPosts() { + return jsonPlaceHolderClient.getPosts(); + } + + @Override + public Post getPostById(Long id) { + return jsonPlaceHolderClient.getPostById(id); + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties new file mode 100644 index 000000000000..41bbbde2c3c8 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.application.name= openfeign +logging.level.com.baeldung.cloud.openfeign.client: DEBUG +feign.hystrix.enabled=true diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignUnitTest.java new file mode 100644 index 000000000000..72d2baa5d770 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenfeignUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.cloud.openfeign; + +import com.baeldung.cloud.openfeign.model.Post; +import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class OpenfeignUnitTest { + + @Autowired + private JSONPlaceHolderService jsonPlaceHolderService; + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @Test + public void whenGetPosts_thenListPostSizeGreaterThanZero() { + + List posts = jsonPlaceHolderService.getPosts(); + + assertFalse(posts.isEmpty()); + } + + @Test + public void whenGetPostWithId_thenPostExist() { + + Post post = jsonPlaceHolderService.getPostById(1L); + + assertNotNull(post); + } + +} diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index abfb0d06f36e..3466f657be24 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -65,22 +65,11 @@ - - - spring-milestones - Spring Milestones - http://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 1.8 - Greenwich.M3 + Greenwich.RELEASE diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsErrorHandler.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsErrorHandler.java new file mode 100644 index 000000000000..220b2744f3cd --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsErrorHandler.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.jms; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.ErrorHandler; + +public class SampleJmsErrorHandler implements ErrorHandler { + + private static final Logger LOG = LoggerFactory.getLogger(SampleJmsErrorHandler.class); + + @Override + public void handleError(Throwable t) { + LOG.warn("In default jms error handler..."); + LOG.error("Error Message : {}", t.getMessage()); + } + +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index 927762f05bce..d3f09618fbcc 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -26,4 +26,8 @@ public void simpleSend() { public void sendMessage(final Employee employee) { this.jmsTemplate.convertAndSend(employee); } + + public void sendTextMessage(String msg) { + this.jmsTemplate.send(queue, s -> s.createTextMessage(msg)); + } } diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java index f35c22e144a8..87627c47e735 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -27,6 +27,9 @@ public void onMessage(Message message) { try { String msg = ((TextMessage) message).getText(); System.out.println("Received message: " + msg); + if (msg == null) { + throw new IllegalArgumentException("Null value received..."); + } } catch (JMSException ex) { throw new RuntimeException(ex); } @@ -37,4 +40,5 @@ public Employee receiveMessage() throws JMSException { Map map = (Map) this.jmsTemplate.receiveAndConvert(); return new Employee((String) map.get("name"), (Integer) map.get("age")); } + } diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml index 28bf848e59cd..97a90e0bf219 100644 --- a/spring-jms/src/main/resources/applicationContext.xml +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -1,51 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderIntegrationTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderIntegrationTest.java index f87d26b14456..f23ead4d6962 100644 --- a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderIntegrationTest.java +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderIntegrationTest.java @@ -8,12 +8,14 @@ public class DefaultTextMessageSenderIntegrationTest { private static SampleJmsMessageSender messageProducer; + private static SampleListener messageListener; @SuppressWarnings("resource") @BeforeClass public static void setUp() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + messageListener = (SampleListener) applicationContext.getBean("messageListener"); } @Test @@ -21,4 +23,9 @@ public void testSimpleSend() { messageProducer.simpleSend(); } + @Test + public void testSendTextMessage() { + messageProducer.sendTextMessage(null); + } + } diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index 755e0932fc49..cd4ad5aba20e 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -8,3 +8,4 @@ - [Guide to Spring Email](http://www.baeldung.com/spring-email) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) +- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java new file mode 100644 index 000000000000..645b36c2a5dd --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.controller; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import javax.validation.ConstraintViolationException; + +@ControllerAdvice +public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(value = {ConstraintViolationException.class}) + protected ResponseEntity handleConstraintViolation(ConstraintViolationException e, WebRequest request) { + return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request); + } +} + diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml index 104712c3d75a..ec237ca8150d 100644 --- a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-remoting-hessian-burlap-client - spring-remoting-hessian-burlap-client + remoting-hessian-burlap-client + remoting-hessian-burlap-client remoting-hessian-burlap diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index ddc7e042b5db..ee6e5dbe3ef2 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -158,11 +158,6 @@ com.fasterxml.jackson.core jackson-databind - - com.thoughtworks.xstream - xstream - ${xstream.version} - diff --git a/spring-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java deleted file mode 100644 index c0639acef449..000000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.web.error; - -import org.baeldung.web.exception.MyResourceNotFoundException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; - -@ControllerAdvice -public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { - - public RestResponseEntityExceptionHandler() { - super(); - } - - @ExceptionHandler(value = { MyResourceNotFoundException.class }) - protected ResponseEntity handleNotFound(final RuntimeException ex, final WebRequest request) { - final String bodyOfResponse = "This should be application specific"; - return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java deleted file mode 100644 index b2137aeeff08..000000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/util/LinkUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.util; - -import javax.servlet.http.HttpServletResponse; - -/** - * Provides some constants and utility methods to build a Link Header to be stored in the {@link HttpServletResponse} object - */ -public final class LinkUtil { - - public static final String REL_COLLECTION = "collection"; - public static final String REL_NEXT = "next"; - public static final String REL_PREV = "prev"; - public static final String REL_FIRST = "first"; - public static final String REL_LAST = "last"; - - private LinkUtil() { - throw new AssertionError(); - } - - // - - /** - * Creates a Link Header to be stored in the {@link HttpServletResponse} to provide Discoverability features to the user - * - * @param uri - * the base uri - * @param rel - * the relative path - * - * @return the complete url - */ - public static String createLinkHeader(final String uri, final String rel) { - return "<" + uri + ">; rel=\"" + rel + "\""; - } - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java deleted file mode 100644 index 5aa0f5a7685b..000000000000 --- a/spring-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.baeldung.common.web; - -import static org.baeldung.Consts.APPLICATION_PORT; -import io.restassured.RestAssured; -import io.restassured.response.Response; - -import java.io.Serializable; - -import org.baeldung.test.IMarshaller; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.common.base.Preconditions; -import com.google.common.net.HttpHeaders; - -public abstract class AbstractLiveTest { - - protected final Class clazz; - - @Autowired - protected IMarshaller marshaller; - - public AbstractLiveTest(final Class clazzToSet) { - super(); - - Preconditions.checkNotNull(clazzToSet); - clazz = clazzToSet; - } - - // template method - - public abstract void create(); - - public abstract String createAsUri(); - - protected final void create(final T resource) { - createAsUri(resource); - } - - protected final String createAsUri(final T resource) { - final Response response = createAsResponse(resource); - Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode()); - - final String locationOfCreatedResource = response.getHeader(HttpHeaders.LOCATION); - Preconditions.checkNotNull(locationOfCreatedResource); - return locationOfCreatedResource; - } - - final Response createAsResponse(final T resource) { - Preconditions.checkNotNull(resource); - - final String resourceAsString = marshaller.encode(resource); - return RestAssured.given() - .contentType(marshaller.getMime()) - .body(resourceAsString) - .post(getURL()); - } - - // - - protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/spring-rest-full/auth/foos"; - } - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java deleted file mode 100644 index 77603da0dd99..000000000000 --- a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@ComponentScan("org.baeldung.test") -public class ConfigIntegrationTest extends WebMvcConfigurerAdapter { - - public ConfigIntegrationTest() { - super(); - } - - // API - -} \ No newline at end of file diff --git a/spring-rest-full/src/test/java/org/baeldung/test/IMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/IMarshaller.java deleted file mode 100644 index 1eefbe87898f..000000000000 --- a/spring-rest-full/src/test/java/org/baeldung/test/IMarshaller.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.test; - -import java.util.List; - -public interface IMarshaller { - - String encode(final T entity); - - T decode(final String entityAsString, final Class clazz); - - List decodeList(final String entitiesAsString, final Class clazz); - - String getMime(); - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java deleted file mode 100644 index 912ad89ed7fa..000000000000 --- a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.baeldung.test; - -import java.io.IOException; -import java.util.List; - -import org.baeldung.persistence.model.Foo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.MediaType; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Preconditions; - -public final class JacksonMarshaller implements IMarshaller { - private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class); - - private final ObjectMapper objectMapper; - - public JacksonMarshaller() { - super(); - - objectMapper = new ObjectMapper(); - } - - // API - - @Override - public final String encode(final T resource) { - Preconditions.checkNotNull(resource); - String entityAsJSON = null; - try { - entityAsJSON = objectMapper.writeValueAsString(resource); - } catch (final IOException ioEx) { - logger.error("", ioEx); - } - - return entityAsJSON; - } - - @Override - public final T decode(final String resourceAsString, final Class clazz) { - Preconditions.checkNotNull(resourceAsString); - - T entity = null; - try { - entity = objectMapper.readValue(resourceAsString, clazz); - } catch (final IOException ioEx) { - logger.error("", ioEx); - } - - return entity; - } - - @SuppressWarnings("unchecked") - @Override - public final List decodeList(final String resourcesAsString, final Class clazz) { - Preconditions.checkNotNull(resourcesAsString); - - List entities = null; - try { - if (clazz.equals(Foo.class)) { - entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { - // ... - }); - } else { - entities = objectMapper.readValue(resourcesAsString, List.class); - } - } catch (final IOException ioEx) { - logger.error("", ioEx); - } - - return entities; - } - - @Override - public final String getMime() { - return MediaType.APPLICATION_JSON.toString(); - } - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java b/spring-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java deleted file mode 100644 index 11273276cdf2..000000000000 --- a/spring-rest-full/src/test/java/org/baeldung/test/TestMarshallerFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.test; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Profile("test") -public class TestMarshallerFactory implements FactoryBean { - - @Autowired - private Environment env; - - public TestMarshallerFactory() { - super(); - } - - // API - - @Override - public IMarshaller getObject() { - final String testMime = env.getProperty("test.mime"); - if (testMime != null) { - switch (testMime) { - case "json": - return new JacksonMarshaller(); - case "xml": - return new XStreamMarshaller(); - default: - throw new IllegalStateException(); - } - } - - return new JacksonMarshaller(); - } - - @Override - public Class getObjectType() { - return IMarshaller.class; - } - - @Override - public boolean isSingleton() { - return true; - } -} \ No newline at end of file diff --git a/spring-security-mvc-jsonview/README.md b/spring-security-mvc-jsonview/README.md new file mode 100644 index 000000000000..35c806e85681 --- /dev/null +++ b/spring-security-mvc-jsonview/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Filtering Jackson JSON Output Based on Spring Security Role](https://www.baeldung.com/spring-security-role-filter-json) diff --git a/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java index 511a6078f5d7..df5313580a94 100644 --- a/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java +++ b/spring-sleuth/src/main/java/com/baeldung/spring/session/SleuthService.java @@ -28,7 +28,7 @@ public void doSomeWorkSameSpan() throws InterruptedException { public void doSomeWorkNewSpan() throws InterruptedException { logger.info("I'm in the original span"); - Span newSpan = tracer.newTrace().name("newSpan").start(); + Span newSpan = tracer.nextSpan().name("newSpan").start(); try (SpanInScope ws = tracer.withSpanInScope(newSpan.start())) { Thread.sleep(1000L); logger.info("I'm in the new span doing some cool work that needs its own span"); diff --git a/spring-sleuth/src/main/resources/logback.xml b/spring-sleuth/src/main/resources/logback.xml index 7d900d8ea884..044adaaf1d90 100644 --- a/spring-sleuth/src/main/resources/logback.xml +++ b/spring-sleuth/src/main/resources/logback.xml @@ -1,13 +1,20 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/README.md b/spring-soap/README.md new file mode 100644 index 000000000000..8d96350e1ec2 --- /dev/null +++ b/spring-soap/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Creating a SOAP Web Service with Spring](https://www.baeldung.com/spring-boot-soap-web-service) diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index f5c3a1434d18..ba05eddf5dac 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -2,9 +2,8 @@ 4.0.0 - - com.baeldung spring-soap + spring-soap 1.0.0 diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index d00a93216826..fbbbdddbf7ef 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -38,22 +38,11 @@ - 2.1.0.RC3 + 2.1.0.RELEASE 3.5 2.6 - - - spring-milestones - Spring Milestones - http://repo.spring.io/milestone - - false - - - - \ No newline at end of file diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml index 2a058e535869..d6097af2086c 100644 --- a/testing-modules/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -48,9 +48,9 @@ - 1.0-groovy-2.4 + 1.3-RC1-groovy-2.4 2.4.7 1.5 - \ No newline at end of file + diff --git a/testing-modules/groovy-spock/src/main/java/mocks/EventPublisher.java b/testing-modules/groovy-spock/src/main/java/mocks/EventPublisher.java new file mode 100644 index 000000000000..290966db9f6f --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/EventPublisher.java @@ -0,0 +1,7 @@ +package mocks; + +public interface EventPublisher { + + void publish(String addedOfferId); + +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/ExternalItemProviderException.java b/testing-modules/groovy-spock/src/main/java/mocks/ExternalItemProviderException.java new file mode 100644 index 000000000000..e2ac43b7f4eb --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/ExternalItemProviderException.java @@ -0,0 +1,5 @@ +package mocks; + +public class ExternalItemProviderException extends RuntimeException { + +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/Item.java b/testing-modules/groovy-spock/src/main/java/mocks/Item.java new file mode 100644 index 000000000000..e1608cfd2332 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/Item.java @@ -0,0 +1,36 @@ +package mocks; + +import java.util.Objects; + +public class Item { + private final String id; + private final String name; + + public Item(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Item item = (Item) o; + return Objects.equals(id, item.id) && + Objects.equals(name, item.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/ItemProvider.java b/testing-modules/groovy-spock/src/main/java/mocks/ItemProvider.java new file mode 100644 index 000000000000..a794c51f4987 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/ItemProvider.java @@ -0,0 +1,9 @@ +package mocks; + +import java.util.List; + +public interface ItemProvider { + + List getItems(List itemIds); + +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/ItemService.java b/testing-modules/groovy-spock/src/main/java/mocks/ItemService.java new file mode 100644 index 000000000000..3327a8b27cd2 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/ItemService.java @@ -0,0 +1,37 @@ +package mocks; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +public class ItemService { + private final ItemProvider itemProvider; + private final EventPublisher eventPublisher; + + + public ItemService(ItemProvider itemProvider, EventPublisher eventPublisher) { + this.itemProvider = itemProvider; + this.eventPublisher = eventPublisher; + } + + List getAllItemsSortedByName(List itemIds) { + List items; + try{ + items = itemProvider.getItems(itemIds); + } catch (RuntimeException ex) { + throw new ExternalItemProviderException(); + } + return items.stream() + .sorted(Comparator.comparing(Item::getName)) + .collect(Collectors.toList()); + } + + void saveItems(List itemIds) { + List notEmptyOfferIds = itemIds.stream() + .filter(itemId -> !itemId.isEmpty()) + .collect(Collectors.toList()); + // save in database + notEmptyOfferIds.forEach(eventPublisher::publish); + } + +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/LoggingEventPublisher.java b/testing-modules/groovy-spock/src/main/java/mocks/LoggingEventPublisher.java new file mode 100644 index 000000000000..c51fe1ff7726 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/LoggingEventPublisher.java @@ -0,0 +1,10 @@ +package mocks; + +public class LoggingEventPublisher implements EventPublisher { + + @Override + public void publish(String addedOfferId) { + System.out.println("I've published: " + addedOfferId); + } + +} diff --git a/testing-modules/groovy-spock/src/test/groovy/mocks/ItemServiceUnitTest.groovy b/testing-modules/groovy-spock/src/test/groovy/mocks/ItemServiceUnitTest.groovy new file mode 100644 index 000000000000..2ccb72f72685 --- /dev/null +++ b/testing-modules/groovy-spock/src/test/groovy/mocks/ItemServiceUnitTest.groovy @@ -0,0 +1,131 @@ +package mocks + +import spock.lang.Specification + +class ItemServiceUnitTest extends Specification { + + ItemProvider itemProvider + ItemService itemService + EventPublisher eventPublisher + + def setup() { + itemProvider = Stub(ItemProvider) + eventPublisher = Mock(EventPublisher) + itemService = new ItemService(itemProvider, eventPublisher) + } + + def 'should return items sorted by name'() { + given: + def ids = ['offer-id', 'offer-id-2'] + itemProvider.getItems(ids) >> [new Item('offer-id-2', 'Zname'), new Item('offer-id', 'Aname')] + + when: + List items = itemService.getAllItemsSortedByName(ids) + + then: + items.collect { it.name } == ['Aname', 'Zname'] + } + + def 'arguments constraints'() { + itemProvider.getItems(['offer-id']) + itemProvider.getItems(_) >> [] + itemProvider.getItems(*_) >> [] + itemProvider.getItems(!null) >> [] + itemProvider.getItems({ it.size > 0 }) >> [] + } + + def 'should return different items on subsequent call'() { + given: + itemProvider.getItems(_) >>> [ + [], + [new Item('1', 'name')], + [new Item('2', 'name')] + ] + + when: 'method is called for the first time' + List items = itemService.getAllItemsSortedByName(['not-important']) + + then: 'empty list is returned' + items == [] + + when: 'method is called for the second time' + items = itemService.getAllItemsSortedByName(['not-important']) + + then: 'item with id=1 is returned' + items == [new Item('1', 'name')] + + when: 'method is called for the thirdtime' + items = itemService.getAllItemsSortedByName(['not-important']) + + then: 'item with id=2 is returned' + items == [new Item('2', 'name')] + } + + def 'should throw ExternalItemProviderException when ItemProvider fails'() { + given: + itemProvider.getItems(_) >> { new RuntimeException()} + + when: + itemService.getAllItemsSortedByName([]) + + then: + thrown(ExternalItemProviderException) + } + + def 'chaining response'() { + itemProvider.getItems(_) >>> { new RuntimeException() } >> new SocketTimeoutException() >> [new Item('id', 'name')] + } + + def 'should return different items for different ids lists'() { + given: + def firstIds = ['first'] + def secondIds = ['second'] + itemProvider.getItems(firstIds) >> [new Item('first', 'Zname')] + itemProvider.getItems(secondIds) >> [new Item('second', 'Aname')] + + when: + def firstItems = itemService.getAllItemsSortedByName(firstIds) + def secondItems = itemService.getAllItemsSortedByName(secondIds) + + then: + firstItems.first().name == 'Zname' + secondItems.first().name == 'Aname' + } + + def 'should publish events about new non-empty saved offers'() { + given: + def offerIds = ['', 'a', 'b'] + + when: + itemService.saveItems(offerIds) + + then: + 2 * eventPublisher.publish({ it != null && !it.isEmpty()}) + } + + def 'should return items'() { + given: + itemProvider = Mock(ItemProvider) + itemProvider.getItems(['item-id']) >> [new Item('item-id', 'name')] + itemService = new ItemService(itemProvider, eventPublisher) + + when: + def items = itemService.getAllItemsSortedByName(['item-id']) + + then: + items == [new Item('item-id', 'name')] + } + + def 'should spy on EventPublisher method call'() { + given: + LoggingEventPublisher eventPublisher = Spy(LoggingEventPublisher) + itemService = new ItemService(itemProvider, eventPublisher) + + when: + itemService.saveItems(['item-id']) + + then: + 1 * eventPublisher.publish('item-id') + } + +} diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index abd50261e793..d686396a1ddd 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -17,3 +17,4 @@ - [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) - [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) +- [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 02ab7b24bd82..8eb282643a5a 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -3,3 +3,4 @@ - [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) - [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) +- [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation)