diff --git a/apache-poi/README.md b/apache-poi/README.md index 599b21e063..d500787536 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -11,3 +11,4 @@ This module contains articles about Apache POI - [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value) - [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula) - [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas) +- [Insert a Row in Excel Using Apache POI](https://www.baeldung.com/apache-poi-insert-excel-row) diff --git a/core-java-modules/core-java-10/README.md b/core-java-modules/core-java-10/README.md index 11c2051816..9a110449bc 100644 --- a/core-java-modules/core-java-10/README.md +++ b/core-java-modules/core-java-10/README.md @@ -11,3 +11,4 @@ This module contains articles about Java 10 core features - [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) - [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list) - [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception) +- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) diff --git a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/streams/StreamToImmutableJava10UnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/streams/StreamToImmutableJava10UnitTest.java new file mode 100644 index 0000000000..8b1ef54fd2 --- /dev/null +++ b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/streams/StreamToImmutableJava10UnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.java10.streams; + +import static java.util.stream.Collectors.toUnmodifiableList; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class StreamToImmutableJava10UnitTest { + + @Test + public void whenUsingCollectorsToUnmodifiableList_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(toUnmodifiableList()); + + System.out.println(result.getClass()); + } +} diff --git a/core-java-modules/core-java-collections-4/README.md b/core-java-modules/core-java-collections-4/README.md index 6e117c98b1..4fd77473d4 100644 --- a/core-java-modules/core-java-collections-4/README.md +++ b/core-java-modules/core-java-collections-4/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap) +- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack) diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java index bd37e5e74e..5dd1eaef09 100644 --- a/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java @@ -8,6 +8,7 @@ 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.List; import java.util.concurrent.TimeUnit; @@ -18,12 +19,12 @@ import java.util.concurrent.TimeUnit; @State(Scope.Thread) public class PrimitivesListPerformance { - private List arrayList = new ArrayList<>(); - private TIntArrayList tList = new TIntArrayList(); - private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); - private IntArrayList fastUtilList = new IntArrayList(); + private List arrayList = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); + private TIntArrayList tList = new TIntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + private IntArrayList fastUtilList = new IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); - private int getValue = 10; + private int getValue = 4; @Benchmark public boolean addArrayList() { diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md index 8b84ecbf81..530a9310c2 100644 --- a/core-java-modules/core-java-collections-maps-3/README.md +++ b/core-java-modules/core-java-collections-maps-3/README.md @@ -8,4 +8,5 @@ This module contains articles about Map data structures in Java. - [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent) - [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap) - [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor) +- [Converting java.util.Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java index 7ee849b0a2..ce96c107f8 100644 --- a/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java +++ b/core-java-modules/core-java-concurrency-collections/src/test/java/com/baeldung/java/stream/ThreadPoolInParallelStreamIntegrationTest.java @@ -21,14 +21,16 @@ public class ThreadPoolInParallelStreamIntegrationTest { long lastNum = 1_000_000; List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); - ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool - .submit(() -> aList.parallelStream() - .reduce(0L, Long::sum)) - .get(); - assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + try { + long actualTotal = customThreadPool + .submit(() -> aList.parallelStream().reduce(0L, Long::sum)) + .get(); + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + } finally { + customThreadPool.shutdown(); + } } @Test diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/filetoinputstream/JavaXToInputStreamUnitTest.java b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/filetoinputstream/JavaXToInputStreamUnitTest.java index caedd1747b..c20752639f 100644 --- a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/filetoinputstream/JavaXToInputStreamUnitTest.java +++ b/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/filetoinputstream/JavaXToInputStreamUnitTest.java @@ -5,12 +5,12 @@ import com.google.common.io.CharSource; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; -import org.apache.commons.io.input.ReaderInputStream; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; +import java.nio.charset.StandardCharsets; public class JavaXToInputStreamUnitTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); @@ -28,7 +28,7 @@ public class JavaXToInputStreamUnitTest { @Test public final void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException { final String initialString = "text"; - final InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream()); + final InputStream targetStream = CharSource.wrap(initialString).asByteSource(StandardCharsets.UTF_8).openStream(); IOUtils.closeQuietly(targetStream); } diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 08e536998c..17ff2f658f 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -77,7 +77,6 @@ 3.6.1 3.27.0-GA - 2.1.0.1 1.8.0 0.10 8.0.1 diff --git a/core-java-modules/core-java-lang-4/README.md b/core-java-modules/core-java-lang-4/README.md new file mode 100644 index 0000000000..77d14f0fc8 --- /dev/null +++ b/core-java-modules/core-java-lang-4/README.md @@ -0,0 +1,5 @@ +## Core Java Lang (Part 4) + +This module contains articles about core features in the Java language + +- [The Java final Keyword – Impact on Performance](https://www.baeldung.com/java-final-performance) diff --git a/core-java-modules/core-java-lang-4/pom.xml b/core-java-modules/core-java-lang-4/pom.xml new file mode 100644 index 0000000000..3e92e9f9c7 --- /dev/null +++ b/core-java-modules/core-java-lang-4/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + core-java-lang-4 + 0.1.0-SNAPSHOT + core-java-lang-4 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + test + + + + + core-java-lang-4 + + + src/main/resources + true + + + + + + 1.28 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/BenchmarkRunner.java b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/BenchmarkRunner.java new file mode 100644 index 0000000000..ee34114195 --- /dev/null +++ b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/BenchmarkRunner.java @@ -0,0 +1,34 @@ +package com.baeldung.finalkeyword; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; + +import java.util.concurrent.TimeUnit; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + @Benchmark + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @BenchmarkMode(Mode.AverageTime) + public static String concatNonFinalStrings() { + String x = "x"; + String y = "y"; + return x + y; + } + + @Benchmark + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @BenchmarkMode(Mode.AverageTime) + public static String concatFinalStrings() { + final String x = "x"; + final String y = "y"; + return x + y; + } + +} diff --git a/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableFinal.java b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableFinal.java new file mode 100644 index 0000000000..1aeef76e58 --- /dev/null +++ b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableFinal.java @@ -0,0 +1,19 @@ +package com.baeldung.finalkeyword; + +import java.io.Console; + +public class ClassVariableFinal { + + static final boolean doX = false; + static final boolean doY = true; + + public static void main(String[] args) { + Console console = System.console(); + if (doX) { + console.writer().println("x"); + } else if (doY) { + console.writer().println("y"); + } + } + +} diff --git a/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableNonFinal.java b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableNonFinal.java new file mode 100644 index 0000000000..a6d83a66cb --- /dev/null +++ b/core-java-modules/core-java-lang-4/src/main/java/com/baeldung/finalkeyword/ClassVariableNonFinal.java @@ -0,0 +1,19 @@ +package com.baeldung.finalkeyword; + +import java.io.Console; + +public class ClassVariableNonFinal { + + static boolean doX = false; + static boolean doY = true; + + public static void main(String[] args) { + Console console = System.console(); + if (doX) { + console.writer().println("x"); + } else if (doY) { + console.writer().println("y"); + } + } + +} diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java new file mode 100644 index 0000000000..b140f7085b --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java @@ -0,0 +1,131 @@ +package com.baeldung.classfile; + +import org.apache.commons.lang3.StringUtils; +import com.baeldung.classfile.HelloWorld.HelloSomeone; + +public class Outer { + + // Static Nested class + static class StaticNested { + public String message() { + return "This is a static Nested Class"; + } + } + + // Non-static Nested class + class Nested { + public String message() { + return "This is a non-static Nested Class"; + } + } + + // Local class + public String message() { + class Local { + private String message() { + return "This is a Local Class within a method"; + } + } + Local local = new Local(); + return local.message(); + } + + // Local class within if clause + public String message(String name) { + if (StringUtils.isEmpty(name)) { + class Local { + private String message() { + return "This is a Local Class within if clause"; + } + } + Local local = new Local(); + return local.message(); + } else + return "Welcome to " + name; + } + + // Anonymous Inner class extending a class + public String greet() { + Outer anonymous = new Outer() { + public String greet() { + return "Running Anonymous Class..."; + } + }; + return anonymous.greet(); + } + + // Anonymous inner class implementing an interface + public String greet(String name) { + + HelloWorld helloWorld = new HelloWorld() { + public String greet(String name) { + return "Welcome to " + name; + } + + }; + return helloWorld.greet(name); + } + + // Anonymous inner class implementing nested interface + public String greetSomeone(String name) { + + HelloSomeone helloSomeOne = new HelloSomeone() { + public String greet(String name) { + return "Hello " + name; + } + + }; + return helloSomeOne.greet(name); + } + + // Nested interface within a class + interface HelloOuter { + public String hello(String name); + } + + // Enum within a class + enum Color { + RED, GREEN, BLUE; + } +} + +interface HelloWorld { + + public String greet(String name); + + // Nested class within an interface + class InnerClass { + public String greet(String name) { + return "Inner class within an interface"; + } + } + + // Nested interface within an interfaces + interface HelloSomeone { + public String greet(String name); + } + + // Enum within an interface + enum Directon { + NORTH, SOUTH, EAST, WEST; + } +} + +enum Level { + LOW, MEDIUM, HIGH; + +} + +enum Foods { + + DRINKS, EATS; + + // Enum within Enum + enum DRINKS { + APPLE_JUICE, COLA; + } + + enum EATS { + POTATO, RICE; + } +} diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/classfile/OuterUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/classfile/OuterUnitTest.java new file mode 100644 index 0000000000..3ffe7d561a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/classfile/OuterUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.classfile; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import com.baeldung.classfile.Outer.Nested; + +public class OuterUnitTest { + + @Test + public void when_static_nestedClass_then_verifyOutput() { + Outer.StaticNested nestedClass = new Outer.StaticNested(); + assertEquals("This is a static Nested Class", nestedClass.message()); + } + + @Test + public void when_nestedClass_then_verifyOutput() { + Outer outer = new Outer(); + Nested nestedClass = outer.new Nested(); + assertEquals("This is a non-static Nested Class", nestedClass.message()); + } + + @Test + public void when_localClass_then_verifyOutput() { + Outer outer = new Outer(); + assertEquals("This is a Local Class within a method", outer.message()); + } + + @Test + public void when_localClassInIfClause_then_verifyOutput() { + Outer outer = new Outer(); + assertEquals("Welcome to Baeldung", outer.message("Baeldung")); + assertEquals("This is a Local Class within if clause", outer.message("")); + } + + @Test + public void when_anonymousClass_then_verifyOutput() { + Outer outer = new Outer(); + assertEquals("Running Anonymous Class...", outer.greet()); + } + + @Test + public void when_anonymousClassHelloWorld_then_verifyOutput() { + Outer outer = new Outer(); + assertEquals("Welcome to Baeldung", outer.greet("Baeldung")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/README.md b/core-java-modules/core-java-reflection-2/README.md index 9ed14f08dc..3195cddc42 100644 --- a/core-java-modules/core-java-reflection-2/README.md +++ b/core-java-modules/core-java-reflection-2/README.md @@ -4,3 +4,4 @@ - [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value) - [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static) - [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract) +- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method) diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml index ea76ee8c98..02a806f87c 100644 --- a/core-java-modules/core-java-reflection-2/pom.xml +++ b/core-java-modules/core-java-reflection-2/pom.xml @@ -14,6 +14,15 @@ ../ + + + org.springframework + spring-test + ${spring.version} + test + + + core-java-reflection-2 @@ -40,5 +49,6 @@ 3.8.0 1.8 1.8 + 5.3.4 \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java new file mode 100644 index 0000000000..03d8daabbf --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatemethods/LongArrayUtil.java @@ -0,0 +1,18 @@ +package com.baeldung.reflection.access.privatemethods; + +public class LongArrayUtil { + + public static int indexOf(long[] array, long target) { + return indexOf(array, target, 0, array.length); + } + + private static int indexOf(long[] array, long target, int start, int end) { + for (int i = start; i < end; i++) { + if (array[i] == target) { + return i; + } + } + return -1; + } + +} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java new file mode 100644 index 0000000000..e98eb9ec7f --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatemethods/InvokePrivateMethodsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.reflection.access.privatemethods; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InvokePrivateMethodsUnitTest { + + private final long[] someLongArray = new long[] { 1L, 2L, 1L, 4L, 2L }; + + @Test + void whenSearchingForLongValueInSubsequenceUsingReflection_thenTheCorrectIndexOfTheValueIsReturned() throws Exception { + Method indexOfMethod = LongArrayUtil.class.getDeclaredMethod("indexOf", long[].class, long.class, int.class, int.class); + indexOfMethod.setAccessible(true); + + assertEquals(2, indexOfMethod.invoke(LongArrayUtil.class, someLongArray, 1L, 1, someLongArray.length), "The index should be 2."); + } + + @Test + void whenSearchingForLongValueInSubsequenceUsingSpring_thenTheCorrectIndexOfTheValueIsReturned() throws Exception { + int indexOfSearchTarget = ReflectionTestUtils.invokeMethod(LongArrayUtil.class, "indexOf", someLongArray, 1L, 1, someLongArray.length); + assertEquals(2, indexOfSearchTarget, "The index should be 2."); + } + +} diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index 9b99d624c9..3f9520b888 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -15,4 +15,5 @@ This module contains articles about core Java Security - [Security Context Basics: User, Subject and Principal](https://www.baeldung.com/security-context-basics) - [Java AES Encryption and Decryption](https://www.baeldung.com/java-aes-encryption-decryption) - [InvalidAlgorithmParameterException: Wrong IV Length](https://www.baeldung.com/java-invalidalgorithmparameter-exception) +- [The java.security.egd JVM Option](https://www.baeldung.com/java-security-egd) - More articles: [[<-- prev]](/core-java-modules/core-java-security) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2d342c4216..7dc54bd907 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -82,6 +82,7 @@ core-java-lang core-java-lang-2 core-java-lang-3 + core-java-lang-4 core-java-lang-math core-java-lang-math-2 core-java-lang-math-3 diff --git a/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java b/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java index 6b315265b4..cde07728ba 100644 --- a/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java +++ b/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java @@ -10,10 +10,8 @@ public class CircularBuffer { @SuppressWarnings("unchecked") public CircularBuffer(int capacity) { - this.capacity = (capacity < 1) ? DEFAULT_CAPACITY : capacity; - this.data = (E[]) new Object[capacity]; - + this.data = (E[]) new Object[this.capacity]; this.readSequence = 0; this.writeSequence = -1; } diff --git a/data-structures/src/main/java/com/baeldung/circularlinkedlist/CircularLinkedList.java b/data-structures/src/main/java/com/baeldung/circularlinkedlist/CircularLinkedList.java index 47368d7f15..cf18f0783e 100644 --- a/data-structures/src/main/java/com/baeldung/circularlinkedlist/CircularLinkedList.java +++ b/data-structures/src/main/java/com/baeldung/circularlinkedlist/CircularLinkedList.java @@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory; public class CircularLinkedList { - final Logger LOGGER = LoggerFactory.getLogger(CircularLinkedList.class); + final Logger logger = LoggerFactory.getLogger(CircularLinkedList.class); private Node head = null; private Node tail = null; @@ -42,24 +42,29 @@ public class CircularLinkedList { } public void deleteNode(int valueToDelete) { - Node currentNode = head; - - if (head != null) { - if (currentNode.value == valueToDelete) { - head = head.nextNode; - tail.nextNode = head; - } else { - do { - Node nextNode = currentNode.nextNode; - if (nextNode.value == valueToDelete) { - currentNode.nextNode = nextNode.nextNode; - break; - } - currentNode = currentNode.nextNode; - } while (currentNode != head); - } + if (head == null) { + return; } + do { + Node nextNode = currentNode.nextNode; + if (nextNode.value == valueToDelete) { + if (tail == head) { + head = null; + tail = null; + } else { + currentNode.nextNode = nextNode.nextNode; + if (head == nextNode) { + head = head.nextNode; + } + if (tail == nextNode) { + tail = currentNode; + } + } + break; + } + currentNode = nextNode; + } while (currentNode != head); } public void traverseList() { @@ -68,7 +73,7 @@ public class CircularLinkedList { if (head != null) { do { - LOGGER.info(currentNode.value + " "); + logger.info(currentNode.value + " "); currentNode = currentNode.nextNode; } while (currentNode != head); } diff --git a/data-structures/src/test/java/com/baeldung/circularlinkedlist/CircularLinkedListUnitTest.java b/data-structures/src/test/java/com/baeldung/circularlinkedlist/CircularLinkedListUnitTest.java index 5b0573a1ce..23829df7e9 100644 --- a/data-structures/src/test/java/com/baeldung/circularlinkedlist/CircularLinkedListUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/circularlinkedlist/CircularLinkedListUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.circularlinkedlist; +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - public class CircularLinkedListUnitTest { @Test @@ -23,7 +23,7 @@ public class CircularLinkedListUnitTest { } @Test - public void givenACircularLinkedList_WhenDeletingElements_ThenListDoesNotContainThoseElements() { + public void givenACircularLinkedList_WhenDeletingInOrderHeadMiddleTail_ThenListDoesNotContainThoseElements() { CircularLinkedList cll = createCircularLinkedList(); assertTrue(cll.containsNode(13)); @@ -39,6 +39,32 @@ public class CircularLinkedListUnitTest { assertFalse(cll.containsNode(46)); } + @Test + public void givenACircularLinkedList_WhenDeletingInOrderTailMiddleHead_ThenListDoesNotContainThoseElements() { + CircularLinkedList cll = createCircularLinkedList(); + + assertTrue(cll.containsNode(46)); + cll.deleteNode(46); + assertFalse(cll.containsNode(46)); + + assertTrue(cll.containsNode(1)); + cll.deleteNode(1); + assertFalse(cll.containsNode(1)); + + assertTrue(cll.containsNode(13)); + cll.deleteNode(13); + assertFalse(cll.containsNode(13)); + } + + @Test + public void givenACircularLinkedListWithOneNode_WhenDeletingElement_ThenListDoesNotContainTheElement() { + CircularLinkedList cll = new CircularLinkedList(); + cll.addNode(1); + cll.deleteNode(1); + assertFalse(cll.containsNode(1)); + } + + private CircularLinkedList createCircularLinkedList() { CircularLinkedList cll = new CircularLinkedList(); diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index bd1029c9cf..9b1d8510c2 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -3,3 +3,4 @@ - [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys) - [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array) - [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry) +- [Optimizing HashMap’s Performance](https://www.baeldung.com/java-hashmap-optimize-performance) diff --git a/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java b/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java index 66bfbe49eb..5e4ecb3e76 100644 --- a/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java +++ b/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java @@ -20,7 +20,7 @@ public class JavaRMIIntegrationTest { MessengerServiceImpl server = new MessengerServiceImpl(); server.createStubAndBind(); } catch (RemoteException e) { - fail("Exception Occurred"); + fail("Exception Occurred: " + e); } } @@ -34,11 +34,9 @@ public class JavaRMIIntegrationTest { String expectedMessage = "Server Message"; assertEquals(responseMessage, expectedMessage); - } catch (RemoteException e) { - fail("Exception Occurred"); - } catch (NotBoundException nb) { - fail("Exception Occurred"); - } + } catch (RemoteException | NotBoundException e) { + fail("Exception Occurred: " + e); + }; } } \ No newline at end of file diff --git a/jjwt/README.md b/jjwt/README.md index 25f5a8f6f0..1798d5193b 100644 --- a/jjwt/README.md +++ b/jjwt/README.md @@ -47,3 +47,4 @@ Available commands (assumes httpie - https://github.com/jkbrzt/httpie): ## Relevant articles: - [Supercharge Java Authentication with JSON Web Tokens (JWTs)](https://www.baeldung.com/java-json-web-tokens-jjwt) +- [Decode a JWT Token in Java](https://www.baeldung.com/java-jwt-token-decode) diff --git a/jjwt/pom.xml b/jjwt/pom.xml index aa238fafb5..9d38d1b0e9 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -41,6 +41,12 @@ jjwt ${jjwt.version} + + + org.assertj + assertj-core + test + diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java new file mode 100644 index 0000000000..922d5c0ce5 --- /dev/null +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java @@ -0,0 +1,46 @@ +package io.jsonwebtoken.jjwtfun.util; + +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator; + +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; + +import static io.jsonwebtoken.SignatureAlgorithm.HS256; + +public class JWTDecoderUtil { + + public static String decodeJWTToken(String token) { + Base64.Decoder decoder = Base64.getDecoder(); + + String[] chunks = token.split("\\."); + + String header = new String(decoder.decode(chunks[0])); + String payload = new String(decoder.decode(chunks[1])); + + return header + " " + payload; + } + + public static String decodeJWTToken(String token, String secretKey) throws Exception { + Base64.Decoder decoder = Base64.getDecoder(); + + String[] chunks = token.split("\\."); + + String header = new String(decoder.decode(chunks[0])); + String payload = new String(decoder.decode(chunks[1])); + + String tokenWithoutSignature = chunks[0] + "." + chunks[1]; + String signature = chunks[2]; + + SignatureAlgorithm sa = HS256; + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), sa.getJcaName()); + + DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec); + + if (!validator.isValid(tokenWithoutSignature, signature)) { + throw new Exception("Could not verify JWT token integrity!"); + } + + return header + " " + payload; + } +} diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java new file mode 100644 index 0000000000..3103a6c8a3 --- /dev/null +++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java @@ -0,0 +1,32 @@ +package io.jsonwebtoken.jjwtfun.util; + +import io.jsonwebtoken.SignatureAlgorithm; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class JWTDecoderUtilUnitTest { + + private final static String SIMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9"; + private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.qH7Zj_m3kY69kxhaQXTa-ivIpytKXXjZc1ZSmapZnGE"; + + @Test + void givenSimpleToken_whenDecoding_thenStringOfHeaderPayloadAreReturned() { + assertThat(JWTDecoderUtil.decodeJWTToken(SIMPLE_TOKEN)) + .contains(SignatureAlgorithm.HS256.getValue()); + } + + @Test + void givenSignedToken_whenDecodingWithInvalidSecret_thenIntegrityIsNotValidated() { + assertThatThrownBy(() -> JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "BAD_SECRET")) + .hasMessage("Could not verify JWT token integrity!"); + } + + @Test + void givenSignedToken_whenDecodingWithValidSecret_thenIntegrityIsValidated() throws Exception { + assertThat(JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "MySecretKey")) + .contains("Baeldung User"); + } +} diff --git a/jmeter/README.md b/jmeter/README.md index 11351ffdda..53aca8d34b 100644 --- a/jmeter/README.md +++ b/jmeter/README.md @@ -52,3 +52,4 @@ Enjoy it :) - [Intro to Performance Testing using JMeter](https://www.baeldung.com/jmeter) - [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/jenkins-and-jmeter) +- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file) diff --git a/kubernetes/k8s-intro/README.md b/kubernetes/k8s-intro/README.md new file mode 100644 index 0000000000..37ca5f3686 --- /dev/null +++ b/kubernetes/k8s-intro/README.md @@ -0,0 +1,13 @@ +# Kubernetes Java API Sample Code + +This module contains sample code used to show how to use the Kubernetes client Java API. + +Before running those samples, make sure that your environment is correctly configured to access +a working Kubernetes cluster. + +An easy way to check that everything is working as expected is issuing any *kubectl get* command: + +```shell +$ kubectl get nodes +``` +If you get a valid response, then you're good to go. \ No newline at end of file diff --git a/kubernetes/k8s-intro/pom.xml b/kubernetes/k8s-intro/pom.xml new file mode 100644 index 0000000000..4a5bb09711 --- /dev/null +++ b/kubernetes/k8s-intro/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + + com.baeldung + kubernetes-parent + 1.0.0-SNAPSHOT + + k8s-intro + 0.0.1-SNAPSHOT + + + + io.kubernetes + client-java + 11.0.0 + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ApiInvoker.java b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ApiInvoker.java new file mode 100644 index 0000000000..fbc2662170 --- /dev/null +++ b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ApiInvoker.java @@ -0,0 +1,11 @@ +package com.baeldung.kubernetes.intro; + +import io.kubernetes.client.openapi.ApiCallback; +import io.kubernetes.client.openapi.ApiException; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import okhttp3.Call; + +@FunctionalInterface +public interface ApiInvoker { + Call apply(CoreV1Api api, ApiCallback callback) throws ApiException; +} diff --git a/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/AsyncHelper.java b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/AsyncHelper.java new file mode 100644 index 0000000000..d9c29dcb64 --- /dev/null +++ b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/AsyncHelper.java @@ -0,0 +1,74 @@ +package com.baeldung.kubernetes.intro; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; +import java.util.function.BiFunction; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.kubernetes.client.openapi.ApiCallback; +import io.kubernetes.client.openapi.ApiException; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import okhttp3.Call; + +public class AsyncHelper implements ApiCallback { + + private static final Logger log = LoggerFactory.getLogger(AsyncHelper.class); + + private CoreV1Api api; + private CompletableFuture callResult; + + private AsyncHelper(CoreV1Api api) { + this.api = api; + } + + public static CompletableFuture doAsync(CoreV1Api api, ApiInvoker invoker) { + + AsyncHelper p = new AsyncHelper<>(api); + return p.execute(invoker); + } + + private CompletableFuture execute( ApiInvoker invoker) { + + try { + callResult = new CompletableFuture<>(); + log.info("[I38] Calling API..."); + final Call call = invoker.apply(api,this); + log.info("[I41] API Succesfully invoked: method={}, url={}", + call.request().method(), + call.request().url()); + return callResult; + } + catch(ApiException aex) { + callResult.completeExceptionally(aex); + return callResult; + } + } + + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + log.error("[E53] onFailure",e); + callResult.completeExceptionally(e); + } + + @Override + public void onSuccess(R result, int statusCode, Map> responseHeaders) { + log.error("[E61] onSuccess: statusCode={}",statusCode); + callResult.complete(result); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + log.info("[E61] onUploadProgress: bytesWritten={}, contentLength={}, done={}",bytesWritten,contentLength,done); + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + log.info("[E75] onDownloadProgress: bytesRead={}, contentLength={}, done={}",bytesRead,contentLength,done); + } +} + diff --git a/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodes.java b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodes.java new file mode 100644 index 0000000000..b0e540eb3a --- /dev/null +++ b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodes.java @@ -0,0 +1,31 @@ +/** + * + */ +package com.baeldung.kubernetes.intro; + + +import io.kubernetes.client.openapi.ApiClient; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import io.kubernetes.client.openapi.models.V1NodeList; +import io.kubernetes.client.util.Config; + +/** + * @author Philippe + * + */ +public class ListNodes { + + /** + * @param args + */ + public static void main(String[] args) throws Exception { + + ApiClient client = Config.defaultClient(); + CoreV1Api api = new CoreV1Api(client); + V1NodeList nodeList = api.listNode(null, null, null, null, null, null, null, null, 10, false); + nodeList.getItems() + .stream() + .forEach((node) -> System.out.println(node.getMetadata())); + } + +} diff --git a/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodesAsync.java b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodesAsync.java new file mode 100644 index 0000000000..acd4512196 --- /dev/null +++ b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListNodesAsync.java @@ -0,0 +1,50 @@ +/** + * + */ +package com.baeldung.kubernetes.intro; + + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.kubernetes.client.openapi.ApiClient; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import io.kubernetes.client.openapi.models.V1NodeList; +import io.kubernetes.client.util.Config; + +/** + * @author Philippe + * + */ +public class ListNodesAsync { + + private static Logger log = LoggerFactory.getLogger(ListNodesAsync.class); + /** + * @param args + */ + public static void main(String[] args) throws Exception { + + // Initial setup + ApiClient client = Config.defaultClient(); + CoreV1Api api = new CoreV1Api(client); + + // Start async call + CompletableFuture p = AsyncHelper.doAsync(api,(capi,cb) -> + capi.listNodeAsync(null, null, null, null, null, null, null, null, 10, false, cb) + ); + + p.thenAcceptAsync((nodeList) -> { + log.info("[I40] Processing results..."); + nodeList.getItems() + .stream() + .forEach((node) -> System.out.println(node.getMetadata())); + }); + + log.info("[I46] Waiting results..."); + p.get(10, TimeUnit.SECONDS); + } + +} diff --git a/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListPodsPaged.java b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListPodsPaged.java new file mode 100644 index 0000000000..1c160ae607 --- /dev/null +++ b/kubernetes/k8s-intro/src/main/java/com/baeldung/kubernetes/intro/ListPodsPaged.java @@ -0,0 +1,46 @@ +/** + * + */ +package com.baeldung.kubernetes.intro; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.kubernetes.client.openapi.ApiClient; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import io.kubernetes.client.openapi.models.V1NodeList; +import io.kubernetes.client.openapi.models.V1PodList; +import io.kubernetes.client.util.Config; + +/** + * @author Philippe + * + */ +public class ListPodsPaged { + + private static final Logger log = LoggerFactory.getLogger(ListPodsPaged.class); + + /** + * @param args + */ + public static void main(String[] args) throws Exception { + + ApiClient client = Config.defaultClient(); + CoreV1Api api = new CoreV1Api(client); + String continuationToken = null; + int limit = 2; // Just for illustration purposes. Real world values would range from ~100 to ~1000/page + Long remaining = null; + do { + log.info("=========================================================================="); + log.info("Retrieving data: continuationToken={}, remaining={}", continuationToken,remaining); + V1PodList items = api.listPodForAllNamespaces(null, continuationToken, null, null, limit, null, null, null, 10, false); + continuationToken = items.getMetadata().getContinue(); + remaining = items.getMetadata().getRemainingItemCount(); + items.getItems() + .stream() + .forEach((node) -> System.out.println(node.getMetadata())); + } while( continuationToken != null ); + } + +} diff --git a/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesAsyncLiveTest.java b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesAsyncLiveTest.java new file mode 100644 index 0000000000..af32df8224 --- /dev/null +++ b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesAsyncLiveTest.java @@ -0,0 +1,10 @@ +package com.baeldung.kubernetes.intro; + +import org.junit.jupiter.api.Test; + +class ListNodesAsyncLiveTest { + @Test + void whenListNodes_thenSuccess() throws Exception { + ListNodesAsync.main(new String[] {}); + } +} diff --git a/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesLiveTest.java b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesLiveTest.java new file mode 100644 index 0000000000..84a3efb903 --- /dev/null +++ b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListNodesLiveTest.java @@ -0,0 +1,10 @@ +package com.baeldung.kubernetes.intro; + +import org.junit.jupiter.api.Test; + +class ListNodesLiveTest { + @Test + void whenListNodes_thenSuccess() throws Exception { + ListNodes.main(new String[] {}); + } +} diff --git a/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListPodsPagedLiveTest.java b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListPodsPagedLiveTest.java new file mode 100644 index 0000000000..6fb3c5b32d --- /dev/null +++ b/kubernetes/k8s-intro/src/test/java/com/baeldung/kubernetes/intro/ListPodsPagedLiveTest.java @@ -0,0 +1,10 @@ +package com.baeldung.kubernetes.intro; + +import org.junit.jupiter.api.Test; + +class ListPodsPagedLiveTest { + @Test + void whenListPodsPage_thenSuccess() throws Exception { + ListPodsPaged.main(new String[] {}); + } +} diff --git a/kubernetes/k8s-intro/src/test/resources/logback.xml b/kubernetes/k8s-intro/src/test/resources/logback.xml new file mode 100644 index 0000000000..479545e643 --- /dev/null +++ b/kubernetes/k8s-intro/src/test/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + diff --git a/kubernetes/pom.xml b/kubernetes/pom.xml new file mode 100644 index 0000000000..fe10295e44 --- /dev/null +++ b/kubernetes/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + kubernetes-parent + pom + + k8s-intro + + \ No newline at end of file diff --git a/libraries-http-2/README.md b/libraries-http-2/README.md index c0d6e76f1b..f3fdf1becb 100644 --- a/libraries-http-2/README.md +++ b/libraries-http-2/README.md @@ -7,5 +7,6 @@ This module contains articles about HTTP libraries. - [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) - [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) - [Retrofit 2 – Dynamic URL](https://www.baeldung.com/retrofit-dynamic-url) +- [Adding Interceptors in OkHTTP](https://www.baeldung.com/java-okhttp-interceptors) - More articles [[<-- prev]](/libraries-http) diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index d0bdb26bd4..855008521f 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 libraries-http-2 libraries-http-2 @@ -13,12 +13,17 @@ - + com.squareup.okhttp3 okhttp ${okhttp.version} + + com.squareup.okhttp3 + logging-interceptor + ${okhttp.version} + com.fasterxml.jackson.core jackson-databind @@ -81,9 +86,9 @@ - 3.14.2 + 4.9.1 2.8.5 - 3.14.2 + 4.9.1 1.0.3 9.4.19.v20190610 2.2.11 diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java new file mode 100644 index 0000000000..e9f8db19be --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/CacheControlResponeInterceptor.java @@ -0,0 +1,18 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Response; + +public class CacheControlResponeInterceptor implements Interceptor { + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + return response.newBuilder() + .header("Cache-Control", "no-store") + .build(); + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java new file mode 100644 index 0000000000..73411d947f --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorMessage.java @@ -0,0 +1,21 @@ +package com.baeldung.okhttp.interceptors; + +public class ErrorMessage { + + private final int status; + private final String detail; + + public ErrorMessage(int status, String detail) { + this.status = status; + this.detail = detail; + } + + public int getStatus() { + return status; + } + + public String getDetail() { + return detail; + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java new file mode 100644 index 0000000000..f6c6673705 --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/ErrorResponseInterceptor.java @@ -0,0 +1,32 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import com.google.gson.Gson; + +import okhttp3.Interceptor; +import okhttp3.MediaType; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class ErrorResponseInterceptor implements Interceptor { + + public static final MediaType APPLICATION_JSON = MediaType.get("application/json; charset=utf-8"); + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + + if(!response.isSuccessful()) { + Gson gson = new Gson(); + String body = gson.toJson(new ErrorMessage(response.code(), "The response from the server was not OK")); + ResponseBody responseBody = ResponseBody.create(body, APPLICATION_JSON); + + return response.newBuilder() + .body(responseBody) + .build(); + } + return response; + } + +} diff --git a/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java new file mode 100644 index 0000000000..6d08546eea --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/okhttp/interceptors/SimpleLoggingInterceptor.java @@ -0,0 +1,25 @@ +package com.baeldung.okhttp.interceptors; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class SimpleLoggingInterceptor implements Interceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLoggingInterceptor.class); + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + LOGGER.info("Intercepted headers: {} from URL: {}", request.headers(), request.url()); + + return chain.proceed(request); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java new file mode 100644 index 0000000000..d15b67ad3b --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/okhttp/interceptors/InterceptorIntegrationTest.java @@ -0,0 +1,90 @@ +package com.baeldung.okhttp.interceptors; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Rule; +import org.junit.Test; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; + +public class InterceptorIntegrationTest { + + @Rule + public MockWebServer server = new MockWebServer(); + + @Test + public void givenSimpleLogginInterceptor_whenRequestSent_thenHeadersLogged() throws IOException { + server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addNetworkInterceptor(new SimpleLoggingInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals("Response code should be: ", 200, response.code()); + assertEquals("Body should be: ", "Hello Baeldung Readers!", response.body().string()); + } + } + + @Test + public void givenResponseInterceptor_whenRequestSent_thenCacheControlSetToNoStore() throws IOException { + server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(getHttpLogger()) + .addInterceptor(new CacheControlResponeInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals("Response code should be: ", 200, response.code()); + assertEquals("Body should be: ", "Hello Baeldung Readers!", response.body().string()); + assertEquals("Response cache-control should be", "no-store", response.header("Cache-Control")); + } + } + + @Test + public void givenErrorResponseInterceptor_whenResponseIs500_thenBodyIsJsonWithStatus() throws IOException { + server.enqueue(new MockResponse().setResponseCode(500).setBody("Hello Baeldung Readers!")); + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(getHttpLogger()) + .addInterceptor(new ErrorResponseInterceptor()) + .build(); + + Request request = new Request.Builder() + .url(server.url("/greeting")) + .header("User-Agent", "A Baeldung Reader") + .build(); + + try (Response response = client.newCall(request).execute()) { + assertEquals("Response code should be: ", 500, response.code()); + assertEquals("Body should be: ", "{\"status\":500,\"detail\":\"The response from the server was not OK\"}", + response.body().string()); + } + } + + private HttpLoggingInterceptor getHttpLogger() { + HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); + logger.setLevel(Level.HEADERS); + return logger; + } + +} diff --git a/maven-modules/maven-plugins/jaxws/README.md b/maven-modules/maven-plugins/jaxws/README.md new file mode 100644 index 0000000000..d17df7a5f6 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Generate WSDL Stubs with Maven](https://www.baeldung.com/maven-wsdl-stubs) diff --git a/maven-modules/maven-plugins/jaxws/pom.xml b/maven-modules/maven-plugins/jaxws/pom.xml new file mode 100644 index 0000000000..161c1dc731 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/pom.xml @@ -0,0 +1,45 @@ + + + + maven-plugins + com.baeldung + 0.0.1-SNAPSHOT + + 4.0.0 + + jaxws + + + + org.codehaus.mojo + jaxws-maven-plugin + 2.6 + + + + wsimport + + + + + ${project.basedir}/src/main/resources/ + com.baeldung.soap.ws.client + + ${project.build.directory}/generated-sources/ + + + + + maven-verifier-plugin + ${maven.verifier.version} + + ../input-resources/verifications.xml + false + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryNotFoundException.java b/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryNotFoundException.java new file mode 100644 index 0000000000..c68d65abb1 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.soap.ws.client; + +public class CountryNotFoundException extends RuntimeException { + + public CountryNotFoundException() { + super("Country not found!"); + } +} diff --git a/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryServiceClient.java b/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryServiceClient.java new file mode 100644 index 0000000000..d6175890f9 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/src/main/java/com/baeldung/soap/ws/client/CountryServiceClient.java @@ -0,0 +1,27 @@ +package com.baeldung.soap.ws.client; + +import java.util.Optional; + +public class CountryServiceClient { + + private CountryService countryService; + + public CountryServiceClient(CountryService countryService) { + this.countryService = countryService; + } + + public String getCapitalByCountryName(String countryName) { + return Optional.of(countryService.findByName(countryName)) + .map(Country::getCapital).orElseThrow(CountryNotFoundException::new); + } + + public int getPopulationByCountryName(String countryName) { + return Optional.of(countryService.findByName(countryName)) + .map(Country::getPopulation).orElseThrow(CountryNotFoundException::new); + } + + public Currency getCurrencyByCountryName(String countryName) { + return Optional.of(countryService.findByName(countryName)) + .map(Country::getCurrency).orElseThrow(CountryNotFoundException::new); + } +} diff --git a/maven-modules/maven-plugins/jaxws/src/main/resources/country.wsdl b/maven-modules/maven-plugins/jaxws/src/main/resources/country.wsdl new file mode 100644 index 0000000000..b6efb7087f --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/src/main/resources/country.wsdl @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-plugins/jaxws/src/main/resources/country.xsd b/maven-modules/maven-plugins/jaxws/src/main/resources/country.xsd new file mode 100644 index 0000000000..c94b6047f9 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/src/main/resources/country.xsd @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-plugins/jaxws/src/test/java/com/baeldung/soap/ws/client/CountryServiceClientUnitTest.java b/maven-modules/maven-plugins/jaxws/src/test/java/com/baeldung/soap/ws/client/CountryServiceClientUnitTest.java new file mode 100644 index 0000000000..65c4f39ee4 --- /dev/null +++ b/maven-modules/maven-plugins/jaxws/src/test/java/com/baeldung/soap/ws/client/CountryServiceClientUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.soap.ws.client; + +import org.junit.jupiter.api.*; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CountryServiceClientUnitTest { + + CountryServiceClient countryServiceClient; + CountryService countryService; + + @BeforeEach + void setUp() { + countryService = mock(CountryService.class); + countryServiceClient = new CountryServiceClient(countryService); + } + + @DisplayName("Get capital by country name when country not found") + @Test + void givenCountryDoesNotExist_whenGetCapitalByCountryName_thenThrowsCountryNotFoundException() { + doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); + Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getCapitalByCountryName(any())); + } + + @DisplayName("Get capital by country name when country is India then should return capital") + @Test + void givenCountryIndia_whenGetCapitalByCountryName_thenShouldReturnCapital() { + Country country = mock(Country.class); + + doReturn("New Delhi").when(country).getCapital(); + doReturn(country).when(countryService).findByName("India"); + + Assertions.assertEquals("New Delhi", countryServiceClient.getCapitalByCountryName("India")); + } + + @DisplayName("Get population by country name when country not found") + @Test + void givenCountryDoesNotExist_getPopulationByCountryName_thenThrowsCountryNotFoundException() { + doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); + Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getPopulationByCountryName(any())); + } + + @DisplayName("Get population by country name when country is India then should return population") + @Test + void givenCountryIndia_getPopulationByCountryName_thenShouldReturnPopulation() { + Country country = mock(Country.class); + + doReturn(1000000).when(country).getPopulation(); + doReturn(country).when(countryService).findByName("India"); + + Assertions.assertEquals(1000000, countryServiceClient.getPopulationByCountryName("India")); + } + + @DisplayName("Get currency by country name when country not found") + @Test + void givenCountryDoesNotExist_getCurrencyByCountryName_thenThrowsCountryNotFoundException() { + doThrow(CountryNotFoundException.class).when(countryService).findByName(any()); + Assertions.assertThrows(CountryNotFoundException.class, () -> countryServiceClient.getCurrencyByCountryName(any())); + } + + @DisplayName("Get currency by country name when country is India then should return currency") + @Test + void givenCountryIndia_getCurrencyByCountryName_thenShouldReturnCurrency() { + Country country = mock(Country.class); + + doReturn(Currency.INR).when(country).getCurrency(); + doReturn(country).when(countryService).findByName("India"); + + Assertions.assertEquals(Currency.INR, countryServiceClient.getCurrencyByCountryName("India")); + } + +} \ No newline at end of file diff --git a/maven-modules/maven-plugins/pom.xml b/maven-modules/maven-plugins/pom.xml index 9f28871ec0..20bdb4b45a 100644 --- a/maven-modules/maven-plugins/pom.xml +++ b/maven-modules/maven-plugins/pom.xml @@ -17,6 +17,7 @@ custom-rule maven-enforcer + jaxws diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index ace3e538c9..f5bf8784a9 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -82,7 +82,7 @@ 3.3.0 1.0.22.RELEASE - 2.4.0 + 2.4.3 1.9.1 3.4.0 diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 5893701c68..3219c504d5 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -31,7 +31,7 @@ - 5.2.8.RELEASE + 5.3.3 5.2.3.RELEASE 1.5.10.RELEASE diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java index 7f50aa87f1..8fff82de32 100644 --- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java @@ -50,7 +50,7 @@ public class Application implements CommandLineRunner { LOGGER.info("@@ findByFirstName() call..."); repository.findByFirstName("Franz") .forEach(person -> LOGGER.info(person.toString())); - LOGGER.info("@@ findByFirstName() call..."); + LOGGER.info("@@ updateByFirstName() call..."); repository.updateByFirstName(2L, "Date Inferno"); repository.findAll() .forEach(person -> LOGGER.info(person.toString())); diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java index 2f2329caec..b2f026fa0c 100644 --- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java @@ -1,23 +1,20 @@ package com.baeldung.springdatajdbcintro.repository; -import java.util.List; - +import com.baeldung.springdatajdbcintro.entity.Person; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.baeldung.springdatajdbcintro.entity.Person; +import java.util.List; @Repository -public interface PersonRepository extends CrudRepository { +public interface PersonRepository extends CrudRepository { - @Query("select * from person where first_name=:firstName") - List findByFirstName(@Param("firstName") String firstName); + List findByFirstName(String firstName); @Modifying @Query("UPDATE person SET first_name = :name WHERE id = :id") boolean updateByFirstName(@Param("id") Long id, @Param("name") String name); - } diff --git a/persistence-modules/spring-data-jpa-annotations/README.md b/persistence-modules/spring-data-jpa-annotations/README.md index 1ee579cf6c..3892e75733 100644 --- a/persistence-modules/spring-data-jpa-annotations/README.md +++ b/persistence-modules/spring-data-jpa-annotations/README.md @@ -6,7 +6,6 @@ This module contains articles about annotations used in Spring Data JPA - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) -- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) - [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) - [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) - [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md index 81398b1f00..42fbecc880 100644 --- a/persistence-modules/spring-data-jpa-enterprise/README.md +++ b/persistence-modules/spring-data-jpa-enterprise/README.md @@ -12,6 +12,7 @@ This module contains articles about Spring Data JPA used in enterprise applicati - [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) - [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) - [Partial Data Update with Spring Data](https://www.baeldung.com/spring-data-partial-update) +- [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-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java index 53f692ff28..cfa99414c6 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java @@ -93,6 +93,9 @@ public interface UserRepository extends JpaRepository , UserRepos @Query("delete User u where u.active = false") int deleteDeactivatedUsers(); + @Query("delete User u where u.active = false") + int deleteDeactivatedUsersWithNoModifyingAnnotation(); + @Modifying(clearAutomatically = true, flushAutomatically = true) @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) void addDeletedColumn(); diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java index b2581b8034..e8841d921c 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -3,6 +3,7 @@ package com.baeldung.boot.daos; import org.junit.After; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; @@ -21,6 +22,7 @@ import java.util.function.Predicate; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.*; public class UserRepositoryCommon { @@ -520,6 +522,22 @@ public class UserRepositoryCommon { assertEquals(1, deletedUsersCount); } + @Test + @Transactional + public void givenTwoUsers_whenDeleteDeactivatedUsersWithNoModifyingAnnotation_ThenException() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + assertThatThrownBy(() -> userRepository.deleteDeactivatedUsersWithNoModifyingAnnotation()) + .isInstanceOf(InvalidDataAccessApiUsageException.class); + } + @Test @Transactional public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { diff --git a/pom.xml b/pom.xml index ef1e33cfe8..f202430ccf 100644 --- a/pom.xml +++ b/pom.xml @@ -471,7 +471,7 @@ json-path jsoup jta - + kubernetes language-interop libraries-2 @@ -531,7 +531,7 @@ protobuffer quarkus - quarkus-extension + rabbitmq @@ -992,7 +992,7 @@ protobuffer quarkus - quarkus-extension + rabbitmq @@ -1370,7 +1370,7 @@ 1.6.0 1.8 1.2.17 - 2.1.0.1 + 2.2.2.0 1.19 1.19 1.6.0 diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 7ae7ba6edd..66861a3bb6 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -174,7 +174,7 @@ 1.0 1.0 4.1 - 1.0.3 + 1.1.6 4.0.1 diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/Book.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/Book.java new file mode 100644 index 0000000000..ff0a8a1bb3 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/Book.java @@ -0,0 +1,39 @@ +package com.baeldung.boot.readonlyrepository; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Book +{ + @Id + @GeneratedValue + private Long id; + private String author; + private String title; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/BookReadOnlyRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/BookReadOnlyRepository.java new file mode 100644 index 0000000000..6327ef5a56 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/BookReadOnlyRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.readonlyrepository; + +import java.util.List; + +public interface BookReadOnlyRepository extends ReadOnlyRepository { + + List findByAuthor(String author); + + List findByTitle(String title); +} diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepository.java new file mode 100644 index 0000000000..16f3fd429e --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.boot.readonlyrepository; + +import org.springframework.data.repository.NoRepositoryBean; +import org.springframework.data.repository.Repository; + +import java.util.List; +import java.util.Optional; + +@NoRepositoryBean +public interface ReadOnlyRepository extends Repository { + + Optional findById(ID id); + + List findAll(); +} diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryApplication.java new file mode 100644 index 0000000000..f5a67197ad --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.boot.readonlyrepository; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ReadOnlyRepositoryApplication { + + public static void main(String[] args) { + SpringApplication.run(ReadOnlyRepositoryApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java new file mode 100644 index 0000000000..363b310c8c --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.boot.readonlyrepository; + +import org.springframework.data.repository.CrudRepository; + +public interface BookRepository extends BookReadOnlyRepository, CrudRepository { +} diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryUnitTest.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryUnitTest.java new file mode 100644 index 0000000000..cdb6065f23 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/ReadOnlyRepositoryUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.boot.readonlyrepository; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; +import java.util.NoSuchElementException; + +@SpringBootTest( classes = ReadOnlyRepositoryApplication.class ) +public class ReadOnlyRepositoryUnitTest +{ + @Autowired + private BookRepository bookRepository; + + @Autowired + private BookReadOnlyRepository bookReadOnlyRepository; + + @Test + public void givenBooks_whenUsingReadOnlyRepository_thenGetThem() { + Book aChristmasCarolCharlesDickens = new Book(); + aChristmasCarolCharlesDickens.setTitle("A Christmas Carol"); + aChristmasCarolCharlesDickens.setAuthor("Charles Dickens"); + bookRepository.save(aChristmasCarolCharlesDickens); + + Book greatExpectationsCharlesDickens = new Book(); + greatExpectationsCharlesDickens.setTitle("Great Expectations"); + greatExpectationsCharlesDickens.setAuthor("Charles Dickens"); + bookRepository.save(greatExpectationsCharlesDickens); + + Book greatExpectationsKathyAcker = new Book(); + greatExpectationsKathyAcker.setTitle("Great Expectations"); + greatExpectationsKathyAcker.setAuthor("Kathy Acker"); + bookRepository.save(greatExpectationsKathyAcker); + + List charlesDickensBooks = bookReadOnlyRepository.findByAuthor("Charles Dickens"); + Assertions.assertEquals(2, charlesDickensBooks.size()); + + List greatExpectationsBooks = bookReadOnlyRepository.findByTitle("Great Expectations"); + Assertions.assertEquals(2, greatExpectationsBooks.size()); + + List allBooks = bookReadOnlyRepository.findAll(); + Assertions.assertEquals(3, allBooks.size()); + + Long bookId = allBooks.get(0).getId(); + Book book = bookReadOnlyRepository.findById(bookId).orElseThrow(NoSuchElementException::new); + Assertions.assertNotNull(book); + } +} diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml index 94a4018103..ae546016f2 100644 --- a/spring-boot-modules/spring-boot-deployment/pom.xml +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -84,12 +84,6 @@ ${jquery.version} - - org.springframework.cloud - spring-cloud-context - ${springcloud.version} - - org.apache.httpcomponents httpclient @@ -195,9 +189,7 @@ 2.2 18.0 3.1.7 - 2.0.2.RELEASE 4.5.8 - 2.3.3.RELEASE diff --git a/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/charencoding/controller/CharEncodingCheckControllerUnitTest.java b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/charencoding/controller/CharEncodingCheckControllerUnitTest.java index 6dcbfe390f..8467a25acd 100644 --- a/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/charencoding/controller/CharEncodingCheckControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-mvc-3/src/test/java/com/baeldung/charencoding/controller/CharEncodingCheckControllerUnitTest.java @@ -1,34 +1,35 @@ package com.baeldung.charencoding.controller; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.io.IOException; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.filter.CharacterEncodingFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; -import org.junit.jupiter.api.Test; -import org.springframework.web.filter.CharacterEncodingFilter; +import static org.junit.jupiter.api.Assertions.assertEquals; class CharEncodingCheckControllerUnitTest { @Test void whenCharEncodingFilter_thenVerifyEncoding() throws ServletException, IOException { - HttpServletRequest request = mock(HttpServletRequest.class); - HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = mock(FilterChain.class); - + HttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + FilterChain chain = new MockFilterChain(); + CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); filter.setForceEncoding(true); - + filter.doFilter(request, response, chain); - - verify(request).setCharacterEncoding("UTF-8"); - verify(response).setCharacterEncoding("UTF-8"); + + assertEquals("UTF-8", request.getCharacterEncoding()); + assertEquals("UTF-8", response.getCharacterEncoding()); } } diff --git a/spring-boot-modules/spring-boot-mvc-jersey/README.md b/spring-boot-modules/spring-boot-mvc-jersey/README.md index 07f9e78ea6..192658c4a5 100644 --- a/spring-boot-modules/spring-boot-mvc-jersey/README.md +++ b/spring-boot-modules/spring-boot-mvc-jersey/README.md @@ -5,4 +5,4 @@ This module contains articles about Spring Boot: JAX-RS vs Spring ### Relevant Articles: -- [REST API: JAX-RS vs Spring](https://www.baeldung.com/TBD) +- [REST API: JAX-RS vs Spring](https://www.baeldung.com/rest-api-jax-rs-vs-spring) diff --git a/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/boot/properties/multidocument/StagingMultidocumentFilesIntegrationTest.java b/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/boot/properties/multidocument/StagingMultidocumentFilesIntegrationTest.java index 8040c93ee0..e02d1de272 100644 --- a/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/boot/properties/multidocument/StagingMultidocumentFilesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties-3/src/test/java/com/baeldung/boot/properties/multidocument/StagingMultidocumentFilesIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.boot.properties.multidocument; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; @@ -21,6 +22,7 @@ public class StagingMultidocumentFilesIntegrationTest { private String baelRootProperty; @Test + @Disabled("Fix and update https://www.baeldung.com/spring-boot-yaml-vs-properties article") public void givenProductionProfileActive_whenApplicationStarts_thenDefaultPropertiesUser() { assertThat(baelCustomProperty).isEqualTo("stagingValue"); assertThat(baelRootProperty).isEqualTo("defaultRootLevelValue"); diff --git a/spring-boot-rest-2/README.md b/spring-boot-rest-2/README.md new file mode 100644 index 0000000000..f09159198c --- /dev/null +++ b/spring-boot-rest-2/README.md @@ -0,0 +1,3 @@ +### Relevant Article: + +- [Get All Endpoints in Spring Boot](https://www.baeldung.com/spring-boot-get-all-endpoints) diff --git a/spring-boot-rest-2/pom.xml b/spring-boot-rest-2/pom.xml new file mode 100644 index 0000000000..d74c393f27 --- /dev/null +++ b/spring-boot-rest-2/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + com.baeldung.web + spring-boot-rest-2 + spring-boot-rest-2 + war + Spring Boot Rest Module + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + io.springfox + springfox-boot-starter + 3.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java new file mode 100644 index 0000000000..510e208f9e --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/SpringBootRestApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.endpoint; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootRestApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRestApplication.class, args); + } +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java new file mode 100644 index 0000000000..732b298981 --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/controller/HelloController.java @@ -0,0 +1,15 @@ +package com.baeldung.endpoint.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloController { + + @GetMapping("/hello") + public ResponseEntity hello() { + return ResponseEntity.ok("hello baeldung"); + } + +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java new file mode 100644 index 0000000000..c57f6b5ecd --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/AnnotationDrivenEndpointsListener.java @@ -0,0 +1,27 @@ +package com.baeldung.endpoint.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.util.Map; + +@Configuration +public class AnnotationDrivenEndpointsListener { + private final Logger LOGGER = LoggerFactory.getLogger("AnnotationDrivenEndpointsListener.class"); + + @EventListener + public void handleContextRefresh(ContextRefreshedEvent event) { + ApplicationContext applicationContext = event.getApplicationContext(); + RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext + .getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class); + Map map = requestMappingHandlerMapping.getHandlerMethods(); + map.forEach((key, value) -> LOGGER.info("{} {}", key, value)); + } +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java new file mode 100644 index 0000000000..ae00fc3927 --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/listener/EndpointsListener.java @@ -0,0 +1,27 @@ +package com.baeldung.endpoint.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.util.Map; + +@Configuration +public class EndpointsListener implements ApplicationListener { + private final Logger LOGGER = LoggerFactory.getLogger("EndpointsListener.class"); + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + ApplicationContext applicationContext = event.getApplicationContext(); + RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext + .getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class); + Map map = requestMappingHandlerMapping.getHandlerMethods(); + map.forEach((key, value) -> LOGGER.info("{} {}", key, value)); + } +} diff --git a/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java new file mode 100644 index 0000000000..bd258122cd --- /dev/null +++ b/spring-boot-rest-2/src/main/java/com/baeldung/endpoint/swagger/SpringFoxConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.endpoint.swagger; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +@Configuration +public class SpringFoxConfig { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } +} diff --git a/spring-boot-rest-2/src/main/resources/application.properties b/spring-boot-rest-2/src/main/resources/application.properties new file mode 100644 index 0000000000..5046c9660f --- /dev/null +++ b/spring-boot-rest-2/src/main/resources/application.properties @@ -0,0 +1,2 @@ + +management.endpoints.web.exposure.include=mappings diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index f58be35a76..9fa9ba0333 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -79,7 +79,6 @@ org.springframework.data spring-data-commons - 2.3.0.RELEASE diff --git a/spring-cloud/spring-cloud-zuul/pom.xml b/spring-cloud/spring-cloud-zuul/pom.xml index 6035ba7e59..13834848fe 100644 --- a/spring-cloud/spring-cloud-zuul/pom.xml +++ b/spring-cloud/spring-cloud-zuul/pom.xml @@ -38,6 +38,11 @@ pom import + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + ${spring-cloud-netflix-zuul.version} + @@ -46,10 +51,6 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - com.h2database h2 @@ -79,8 +80,8 @@ - Hoxton.SR4 - 2.3.3.RELEASE + 2020.0.0 + 2.2.2.RELEASE diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml index b42d32b6b3..bb735a71ed 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/pom.xml @@ -19,6 +19,10 @@ spring-cloud-zuul-ratelimit ${rate.limit.version} + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + org.springframework.boot spring-boot-starter-data-jpa diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml index 7978d9c77b..b7e1702558 100644 --- a/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-ui/pom.xml @@ -13,6 +13,10 @@ + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + org.springframework.boot spring-boot-starter-thymeleaf diff --git a/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java new file mode 100644 index 0000000000..b29f9ab0ce --- /dev/null +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/DynamicSchedulingConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.scheduling.dynamic; + +import java.time.Instant; +import java.util.Date; +import java.util.Optional; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.SchedulingConfigurer; +import org.springframework.scheduling.config.ScheduledTaskRegistrar; + +@Configuration +@ComponentScan("com.baeldung.scheduling.dynamic") +@EnableScheduling +public class DynamicSchedulingConfig implements SchedulingConfigurer { + + @Autowired + private TickService tickService; + + @Bean + public Executor taskExecutor() { + return Executors.newSingleThreadScheduledExecutor(); + } + + @Override + public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { + taskRegistrar.setScheduler(taskExecutor()); + taskRegistrar.addTriggerTask( + () -> tickService.tick(), + context -> { + Optional lastCompletionTime = + Optional.ofNullable(context.lastCompletionTime()); + Instant nextExecutionTime = + lastCompletionTime.orElseGet(Date::new).toInstant() + .plusMillis(tickService.getDelay()); + return Date.from(nextExecutionTime); + } + ); + } + +} diff --git a/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/TickService.java b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/TickService.java new file mode 100644 index 0000000000..5da56f33a9 --- /dev/null +++ b/spring-scheduling/src/main/java/com/baeldung/scheduling/dynamic/TickService.java @@ -0,0 +1,22 @@ +package com.baeldung.scheduling.dynamic; + +import org.springframework.stereotype.Service; + +@Service +public class TickService { + + private long delay = 0; + + public long getDelay() { + this.delay += 1000; + System.out.println("delaying " + this.delay + " milliseconds..."); + return this.delay; + } + + public void tick() { + final long now = System.currentTimeMillis() / 1000; + System.out + .println("schedule tasks with dynamic delay - " + now); + } + +} diff --git a/spring-scheduling/src/test/java/com/baeldung/scheduling/DynamicSchedulingIntegrationTest.java b/spring-scheduling/src/test/java/com/baeldung/scheduling/DynamicSchedulingIntegrationTest.java new file mode 100644 index 0000000000..2ff9cfaefa --- /dev/null +++ b/spring-scheduling/src/test/java/com/baeldung/scheduling/DynamicSchedulingIntegrationTest.java @@ -0,0 +1,19 @@ +package com.baeldung.scheduling; + +import com.baeldung.scheduling.dynamic.DynamicSchedulingConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { + DynamicSchedulingConfig.class}, loader = AnnotationConfigContextLoader.class) +public class DynamicSchedulingIntegrationTest { + + @Test + public void testTickServiceTick() throws InterruptedException { + Thread.sleep(6000); + } +} diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 99dea4bc67..096ffb9c3f 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -35,6 +35,7 @@ spring-security-legacy-oidc spring-security-oidc spring-security-okta + spring-security-saml spring-security-web-react spring-security-web-rest spring-security-web-rest-basic-auth diff --git a/spring-security-modules/spring-5-security/pom.xml b/spring-security-modules/spring-5-security/pom.xml index f50b5ff7a9..d009115c92 100644 --- a/spring-security-modules/spring-5-security/pom.xml +++ b/spring-security-modules/spring-5-security/pom.xml @@ -49,7 +49,7 @@ org.owasp.esapi esapi - 2.2.2.0 + ${esapi.version} org.jsoup diff --git a/spring-security-modules/spring-security-saml/README.md b/spring-security-modules/spring-security-saml/README.md new file mode 100644 index 0000000000..271b29632e --- /dev/null +++ b/spring-security-modules/spring-security-saml/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [A Guide to SAML with Spring Security](https://www.baeldung.com/spring-security-saml) diff --git a/spring-security-modules/spring-security-saml/pom.xml b/spring-security-modules/spring-security-saml/pom.xml new file mode 100644 index 0000000000..561582045a --- /dev/null +++ b/spring-security-modules/spring-security-saml/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + spring-security-saml + 1.0-SNAPSHOT + spring-security-saml + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + Shibboleth + Shibboleth + https://build.shibboleth.net/nexus/content/repositories/releases/ + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.security.extensions + spring-security-saml2-core + ${saml2-core.spring.version} + + + + + spring-security-saml + + + src/main/resources + + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + repackage + + + + + + + + + 1.0.10.RELEASE + + diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/Application.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/Application.java new file mode 100644 index 0000000000..39eaa46424 --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.saml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String... args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/authentication/CustomSAMLAuthenticationProvider.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/authentication/CustomSAMLAuthenticationProvider.java new file mode 100644 index 0000000000..b35a72763d --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/authentication/CustomSAMLAuthenticationProvider.java @@ -0,0 +1,28 @@ +package com.baeldung.saml.authentication; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.providers.ExpiringUsernameAuthenticationToken; +import org.springframework.security.saml.SAMLAuthenticationProvider; +import org.springframework.security.saml.SAMLCredential; + +public class CustomSAMLAuthenticationProvider extends SAMLAuthenticationProvider { + + @Override + public Collection getEntitlements(SAMLCredential credential, Object userDetail) { + + if(userDetail instanceof ExpiringUsernameAuthenticationToken) { + List authorities = new ArrayList(); + authorities.addAll(((ExpiringUsernameAuthenticationToken) userDetail).getAuthorities()); + return authorities; + + } else { + return Collections.emptyList(); + } + } + +} diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/SamlSecurityConfig.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/SamlSecurityConfig.java new file mode 100644 index 0000000000..378db478cf --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/SamlSecurityConfig.java @@ -0,0 +1,226 @@ +package com.baeldung.saml.config; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.util.resource.ResourceException; +import org.opensaml.xml.parse.StaticBasicParserPool; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.security.saml.*; +import org.springframework.security.saml.context.SAMLContextProviderImpl; +import org.springframework.security.saml.key.JKSKeyManager; +import org.springframework.security.saml.key.KeyManager; +import org.springframework.security.saml.log.SAMLDefaultLogger; +import org.springframework.security.saml.metadata.CachingMetadataManager; +import org.springframework.security.saml.metadata.ExtendedMetadata; +import org.springframework.security.saml.metadata.ExtendedMetadataDelegate; +import org.springframework.security.saml.processor.*; +import org.springframework.security.saml.util.VelocityFactory; +import org.springframework.security.saml.websso.*; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; + +import com.baeldung.saml.authentication.CustomSAMLAuthenticationProvider; + +@Configuration +public class SamlSecurityConfig { + + @Value("${saml.keystore.location}") + private String samlKeystoreLocation; + + @Value("${saml.keystore.password}") + private String samlKeystorePassword; + + @Value("${saml.keystore.alias}") + private String samlKeystoreAlias; + + @Value("${saml.idp}") + private String defaultIdp; + + @Bean(initMethod = "initialize") + public StaticBasicParserPool parserPool() { + return new StaticBasicParserPool(); + } + + @Bean + public SAMLAuthenticationProvider samlAuthenticationProvider() { + return new CustomSAMLAuthenticationProvider(); + } + + @Bean + public SAMLContextProviderImpl contextProvider() { + return new SAMLContextProviderImpl(); + } + + @Bean + public static SAMLBootstrap samlBootstrap() { + return new SAMLBootstrap(); + } + + @Bean + public SAMLDefaultLogger samlLogger() { + return new SAMLDefaultLogger(); + } + + @Bean + public WebSSOProfileConsumer webSSOprofileConsumer() { + return new WebSSOProfileConsumerImpl(); + } + + @Bean + @Qualifier("hokWebSSOprofileConsumer") + public WebSSOProfileConsumerHoKImpl hokWebSSOProfileConsumer() { + return new WebSSOProfileConsumerHoKImpl(); + } + + @Bean + public WebSSOProfile webSSOprofile() { + return new WebSSOProfileImpl(); + } + + @Bean + public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() { + return new WebSSOProfileConsumerHoKImpl(); + } + + @Bean + public WebSSOProfileECPImpl ecpProfile() { + return new WebSSOProfileECPImpl(); + } + + @Bean + public SingleLogoutProfile logoutProfile() { + return new SingleLogoutProfileImpl(); + } + + @Bean + public KeyManager keyManager() { + DefaultResourceLoader loader = new DefaultResourceLoader(); + Resource storeFile = loader.getResource(samlKeystoreLocation); + Map passwords = new HashMap<>(); + passwords.put(samlKeystoreAlias, samlKeystorePassword); + return new JKSKeyManager(storeFile, samlKeystorePassword, passwords, samlKeystoreAlias); + } + + @Bean + public WebSSOProfileOptions defaultWebSSOProfileOptions() { + WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions(); + webSSOProfileOptions.setIncludeScoping(false); + return webSSOProfileOptions; + } + + @Bean + public SAMLEntryPoint samlEntryPoint() { + SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint(); + samlEntryPoint.setDefaultProfileOptions(defaultWebSSOProfileOptions()); + return samlEntryPoint; + } + + @Bean + public ExtendedMetadata extendedMetadata() { + ExtendedMetadata extendedMetadata = new ExtendedMetadata(); + extendedMetadata.setIdpDiscoveryEnabled(false); + extendedMetadata.setSignMetadata(false); + return extendedMetadata; + } + + @Bean + @Qualifier("okta") + public ExtendedMetadataDelegate oktaExtendedMetadataProvider() throws MetadataProviderException { + File metadata = null; + try { + metadata = new File("./src/main/resources/saml/metadata/sso.xml"); + } catch (Exception e) { + e.printStackTrace(); + } + FilesystemMetadataProvider provider = new FilesystemMetadataProvider(metadata); + provider.setParserPool(parserPool()); + return new ExtendedMetadataDelegate(provider, extendedMetadata()); + } + + @Bean + @Qualifier("metadata") + public CachingMetadataManager metadata() throws MetadataProviderException, ResourceException { + List providers = new ArrayList<>(); + providers.add(oktaExtendedMetadataProvider()); + CachingMetadataManager metadataManager = new CachingMetadataManager(providers); + metadataManager.setDefaultIDP(defaultIdp); + return metadataManager; + } + + @Bean + @Qualifier("saml") + public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() { + SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler = new SavedRequestAwareAuthenticationSuccessHandler(); + successRedirectHandler.setDefaultTargetUrl("/home"); + return successRedirectHandler; + } + + @Bean + @Qualifier("saml") + public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() { + SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); + failureHandler.setUseForward(true); + failureHandler.setDefaultFailureUrl("/error"); + return failureHandler; + } + + @Bean + public SimpleUrlLogoutSuccessHandler successLogoutHandler() { + SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler(); + successLogoutHandler.setDefaultTargetUrl("/"); + return successLogoutHandler; + } + + @Bean + public SecurityContextLogoutHandler logoutHandler() { + SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); + logoutHandler.setInvalidateHttpSession(true); + logoutHandler.setClearAuthentication(true); + return logoutHandler; + } + + @Bean + public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() { + return new SAMLLogoutProcessingFilter(successLogoutHandler(), logoutHandler()); + } + + @Bean + public SAMLLogoutFilter samlLogoutFilter() { + return new SAMLLogoutFilter(successLogoutHandler(), + new LogoutHandler[] { logoutHandler() }, + new LogoutHandler[] { logoutHandler() }); + } + + @Bean + public HTTPPostBinding httpPostBinding() { + return new HTTPPostBinding(parserPool(), VelocityFactory.getEngine()); + } + + @Bean + public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() { + return new HTTPRedirectDeflateBinding(parserPool()); + } + + @Bean + public SAMLProcessorImpl processor() { + ArrayList bindings = new ArrayList<>(); + bindings.add(httpRedirectDeflateBinding()); + bindings.add(httpPostBinding()); + return new SAMLProcessorImpl(bindings); + } +} diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java new file mode 100644 index 0000000000..297c391823 --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java @@ -0,0 +1,152 @@ +package com.baeldung.saml.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.saml.*; +import org.springframework.security.saml.key.KeyManager; +import org.springframework.security.saml.metadata.*; +import org.springframework.security.web.DefaultSecurityFilterChain; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.channel.ChannelProcessingFilter; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(securedEnabled = true) +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Value("${saml.sp}") + private String samlAudience; + + @Autowired + @Qualifier("saml") + private SavedRequestAwareAuthenticationSuccessHandler samlAuthSuccessHandler; + + @Autowired + @Qualifier("saml") + private SimpleUrlAuthenticationFailureHandler samlAuthFailureHandler; + + @Autowired + private SAMLEntryPoint samlEntryPoint; + + @Autowired + private SAMLLogoutFilter samlLogoutFilter; + + @Autowired + private SAMLLogoutProcessingFilter samlLogoutProcessingFilter; + + @Bean + public SAMLDiscovery samlDiscovery() { + SAMLDiscovery idpDiscovery = new SAMLDiscovery(); + return idpDiscovery; + } + + @Autowired + private SAMLAuthenticationProvider samlAuthenticationProvider; + + @Autowired + private ExtendedMetadata extendedMetadata; + + @Autowired + private KeyManager keyManager; + + public MetadataGenerator metadataGenerator() { + MetadataGenerator metadataGenerator = new MetadataGenerator(); + metadataGenerator.setEntityId(samlAudience); + metadataGenerator.setExtendedMetadata(extendedMetadata); + metadataGenerator.setIncludeDiscoveryExtension(false); + metadataGenerator.setKeyManager(keyManager); + return metadataGenerator; + } + + @Bean + public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception { + SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter(); + samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager()); + samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(samlAuthSuccessHandler); + samlWebSSOProcessingFilter.setAuthenticationFailureHandler(samlAuthFailureHandler); + return samlWebSSOProcessingFilter; + } + + @Bean + public FilterChainProxy samlFilter() throws Exception { + List chains = new ArrayList<>(); + chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"), + samlWebSSOProcessingFilter())); + chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"), + samlDiscovery())); + chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"), + samlEntryPoint)); + chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"), + samlLogoutFilter)); + chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"), + samlLogoutProcessingFilter)); + return new FilterChainProxy(chains); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public MetadataGeneratorFilter metadataGeneratorFilter() { + return new MetadataGeneratorFilter(metadataGenerator()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf() + .disable(); + + http + .httpBasic() + .authenticationEntryPoint(samlEntryPoint); + + http + .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class) + .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class) + .addFilterBefore(samlFilter(), CsrfFilter.class); + + http + .authorizeRequests() + .antMatchers("/").permitAll() + .anyRequest().authenticated(); + + http + .logout() + .addLogoutHandler((request, response, authentication) -> { + try { + response.sendRedirect("/saml/logout"); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(samlAuthenticationProvider); + } + +} diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/controller/HomeController.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/controller/HomeController.java new file mode 100644 index 0000000000..e77933b8f3 --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/controller/HomeController.java @@ -0,0 +1,35 @@ +package com.baeldung.saml.controller; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class HomeController { + + @RequestMapping("/") + public String index() { + return "index"; + } + + @GetMapping(value = "/auth") + public String handleSamlAuth() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { + return "redirect:/home"; + } else { + return "/"; + } + } + + @RequestMapping("/home") + public String home(Model model) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("username", authentication.getPrincipal()); + return "home"; + } + +} diff --git a/spring-security-modules/spring-security-saml/src/main/resources/application.properties b/spring-security-modules/spring-security-saml/src/main/resources/application.properties new file mode 100644 index 0000000000..f9d6a5df3c --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/resources/application.properties @@ -0,0 +1,6 @@ +saml.keystore.location=classpath:/saml/samlKeystore.jks +saml.keystore.password= +saml.keystore.alias= + +saml.idp= +saml.sp=http://localhost:8080/saml/metadata \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml/src/main/resources/saml/metadata/sso.xml b/spring-security-modules/spring-security-saml/src/main/resources/saml/metadata/sso.xml new file mode 100644 index 0000000000..2d3258de12 --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/resources/saml/metadata/sso.xml @@ -0,0 +1,44 @@ + + + + + + + MIIDpDCCAoygAwIBAgIGAXGiSQ7ZMA0GCSqGSIb3DQEBCwUAMIGSMQswCQYDVQQGEwJVUzETMBEG + A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU + MBIGA1UECwwLU1NPUHJvdmlkZXIxEzARBgNVBAMMCmRldi05MjY2NjYxHDAaBgkqhkiG9w0BCQEW + DWluZm9Ab2t0YS5jb20wHhcNMjAwNDIyMTQyNjA5WhcNMzAwNDIyMTQyNzA5WjCBkjELMAkGA1UE + BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xDTALBgNV + BAoMBE9rdGExFDASBgNVBAsMC1NTT1Byb3ZpZGVyMRMwEQYDVQQDDApkZXYtOTI2NjY2MRwwGgYJ + KoZIhvcNAQkBFg1pbmZvQG9rdGEuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA + g1rQYYqeVx2gl/UUnLJzp5hrm06VOILJB9hIUmNqXgWV3UjzDq/zX0KW8MENjsO7+S8a+LLnYRkb + N5egH9FSt8AHtB1pmfXDtpUQmWe9yJbNxbCISoc6XzCmaRw3HRv9pK5SciIutciz9lvFaHMWAWtP + MmQSKdhMet52tuf6sTy4ODeXjyMnD9q5QOKww1SJ678wjHbGRRhNvCxvTSAH33sa4oNCf2RvP9hp + NiJRcYW9yLZXmZArPQOuAx5PIXfHhK2e4ac39YO4fgO7gwU5TZ+vL7o6iEmd9tk44PrND0ZV5yzZ + +Y33Hiun3fIiZu/nZZGUjm4k4exl8JJpwrVTHQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBcfHcL + 2DjTjZGoANF4dPpGXTYdVnL/XzGiLS+3LR/HDrEz/EqsHouF40RnzdZ7Ax7RReKBYCUUqHpSE+LU + ductz2ANguzyseGEn72I4Ym4ytQWnFyTXeW+xI9CoCLGfOUhT1hlKjsu/qNM8qwKFPWkzQp7mDN8 + S9MGhsnbiyeD/lceAEKw16Os73/sX2j7F+43WVCYRDCRB8pRIPfcqYLXUIUSstQlwEvCF7HyeO4+ + jxKHA1tp9Cpmj7/VD9TE3fyvrbVmfjTbKjF7/0wYQNfbHDDko0ratDMAizG5/d3i9wk9KbGCHSxT + ph5nl1pdjKgAYPK0iNDnGCZbGKzXOrqV + + + + + urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified + + urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks b/spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks new file mode 100644 index 0000000000..7f3a5850d9 Binary files /dev/null and b/spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks differ diff --git a/spring-security-modules/spring-security-saml/src/main/resources/templates/error.html b/spring-security-modules/spring-security-saml/src/main/resources/templates/error.html new file mode 100644 index 0000000000..7223ee43fd --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/resources/templates/error.html @@ -0,0 +1,13 @@ + + + +
Something went wrong
+
+ +

+ An error occurred +

+
+ + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml/src/main/resources/templates/home.html b/spring-security-modules/spring-security-saml/src/main/resources/templates/home.html new file mode 100644 index 0000000000..c66e92c1f0 --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/resources/templates/home.html @@ -0,0 +1,13 @@ + + + +Baeldung Spring Security SAML: Home + + +

Welcome!
You are successfully logged in!

+

You are logged as null.

+ + Logout + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml/src/main/resources/templates/index.html b/spring-security-modules/spring-security-saml/src/main/resources/templates/index.html new file mode 100644 index 0000000000..7999c2fded --- /dev/null +++ b/spring-security-modules/spring-security-saml/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + +Baeldung Spring Security SAML + + +

Welcome to Baeldung Spring Security SAML

+ Login + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java-2/README.md b/spring-web-modules/spring-mvc-java-2/README.md index 41ff7bdf7c..74d8cca312 100644 --- a/spring-web-modules/spring-mvc-java-2/README.md +++ b/spring-web-modules/spring-mvc-java-2/README.md @@ -6,4 +6,4 @@ - [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) - [Converting a Spring MultipartFile to a File](https://www.baeldung.com/spring-multipartfile-to-file) - [Testing a Spring Multipart POST Request](https://www.baeldung.com/spring-multipart-post-request-test) -- [Spring @Pathvariable Annotation](https://www.baeldung.com/spring-pathvariable) +- [Spring @PathVariable Annotation](https://www.baeldung.com/spring-pathvariable) diff --git a/spring-web-modules/spring-mvc-views/pom.xml b/spring-web-modules/spring-mvc-views/pom.xml index 2c3be5a33e..2e80a60966 100644 --- a/spring-web-modules/spring-mvc-views/pom.xml +++ b/spring-web-modules/spring-mvc-views/pom.xml @@ -11,7 +11,7 @@ com.baeldung parent-spring-5 0.0.1-SNAPSHOT - parent-spring-5/pom.xml + ../../parent-spring-5 diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index 6aa8be365c..0ea3fd6840 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -19,6 +19,10 @@ org.springframework.boot spring-boot-starter-web
+ + org.springframework.boot + spring-boot-starter-webflux + io.springfox springfox-swagger2 @@ -29,6 +33,19 @@ springfox-swagger-ui ${swagger2.version} + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + io.github.resilience4j + resilience4j-timelimiter + 1.6.1 +
diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/RequestTimeoutRestController.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/RequestTimeoutRestController.java new file mode 100644 index 0000000000..d425737bab --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/RequestTimeoutRestController.java @@ -0,0 +1,61 @@ +package com.baeldung.requesttimeout; + +import com.baeldung.requesttimeout.domain.Book; +import com.baeldung.requesttimeout.domain.BookRepository; +import io.github.resilience4j.timelimiter.TimeLimiter; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import java.time.Duration; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; + +@RestController +public class RequestTimeoutRestController { + + private final BookRepository bookRepository; + private final WebClient webClient; + + public RequestTimeoutRestController(BookRepository bookRepository, WebClient webClient) { + this.bookRepository = bookRepository; + this.webClient = webClient; + } + + @GetMapping("/author/transactional") + @Transactional(timeout = 1) + public String getWithTransactionTimeout(@RequestParam String title) { + return getAuthor(title); + } + + private final TimeLimiter ourTimeLimiter = TimeLimiter.of(TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(500)).build()); + @GetMapping("/author/resilience4j") + public Callable getWithResilience4jTimeLimiter(@RequestParam String title) { + return TimeLimiter.decorateFutureSupplier(ourTimeLimiter, () -> CompletableFuture.supplyAsync(() -> getAuthor(title))); + } + + @GetMapping("/author/mvc-request-timeout") + public Callable getWithMvcRequestTimeout(@RequestParam String title) { + return () -> getAuthor(title); + } + + @GetMapping("/author/webclient") + public String getWithWebClient(@RequestParam String title) { + return webClient.get() + .uri(uriBuilder -> uriBuilder + .path("/author/transactional") + .queryParam("title", title) + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String getAuthor(String title) { + bookRepository.wasteTime(); + return bookRepository.findById(title).map(Book::getAuthor).orElse("No book found for this title."); + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/configuration/WebClientConfiguration.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/configuration/WebClientConfiguration.java new file mode 100644 index 0000000000..52b3573411 --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/configuration/WebClientConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.requesttimeout.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import java.time.Duration; + +@Configuration +public class WebClientConfiguration { + + @Bean + public WebClient webClient() { + return WebClient.builder() + .baseUrl("http://localhost:8080") + .clientConnector(new ReactorClientHttpConnector(HttpClient.create().responseTimeout(Duration.ofMillis(250)))) + .build(); + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/Book.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/Book.java new file mode 100644 index 0000000000..846bfb2cec --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/Book.java @@ -0,0 +1,28 @@ +package com.baeldung.requesttimeout.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + private String title; + private String author; + + public void setTitle(String title) { + this.title = title; + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/BookRepository.java b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/BookRepository.java new file mode 100644 index 0000000000..8ecab0f1d2 --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/java/com/baeldung/requesttimeout/domain/BookRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.requesttimeout.domain; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BookRepository extends JpaRepository { + + default int wasteTime() { + int i = Integer.MIN_VALUE; + while(i < Integer.MAX_VALUE) { + i++; + } + return i; + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties b/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties new file mode 100644 index 0000000000..ff4af943ec --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.mvc.async.request-timeout=750 \ No newline at end of file diff --git a/spring-web-modules/spring-rest-http-2/src/test/com/baeldung/requesttimeout/RequestTimeoutUnitTest.java b/spring-web-modules/spring-rest-http-2/src/test/com/baeldung/requesttimeout/RequestTimeoutUnitTest.java new file mode 100644 index 0000000000..da7d40d53c --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/test/com/baeldung/requesttimeout/RequestTimeoutUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.requesttimeout; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientRequestException; + +@SpringBootTest +@RunWith(SpringRunner.class) +public class RequestTimeoutTests { + + private static final WebClient WEB_CLIENT = WebClient.builder().baseUrl("http://localhost:8080").build(); + + @Test(expected = WebClientRequestException.class) + public void givenTransactionTimeout_whenTimeExpires_thenReceiveException() { + getAuthor("transactional"); + } + + @Test(expected = WebClientRequestException.class) + public void givenResilience4jTimeLimiter_whenTimeExpires_thenReceiveException() { + getAuthor("resilience4j"); + } + + @Test(expected = WebClientRequestException.class) + public void givenMvcRequestTimeout_whenTimeExpires_thenReceiveException() { + getAuthor("mvc-request-timeout"); + } + + @Test(expected = WebClientRequestException.class) + public void givenWebClientTimeout_whenTimeExpires_thenReceiveException() { + getAuthor("webclient"); + } + + private void getAuthor(String authorPath) { + WEB_CLIENT.get() + .uri(uriBuilder -> uriBuilder + .path("/author/" + authorPath) + .queryParam("title", "title") + .build()) + .retrieve() + .bodyToMono(String.class) + .block(); + } +} diff --git a/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties b/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties new file mode 100644 index 0000000000..ff4af943ec --- /dev/null +++ b/spring-web-modules/spring-rest-http-2/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.mvc.async.request-timeout=750 \ No newline at end of file diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 9e0c986bb2..74d55d4c08 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -125,7 +125,7 @@ 3.1.6 5.7.0 1.7.0 - 5.3.0 + 5.3.4 4.0.1 2.1.1 diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java index 9b692edd7b..9481c54b48 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java @@ -1,15 +1,14 @@ package com.baeldung.overrideproperties; import com.baeldung.overrideproperties.resolver.PropertySourceResolver; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) +@SpringBootTest @ContextConfiguration(initializers = PropertyOverrideContextInitializer.class, classes = Application.class) public class ContextPropertySourceResolverIntegrationTest { diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java index 815b628f0a..77b882d3a2 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java @@ -1,18 +1,17 @@ package com.baeldung.overrideproperties; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.baeldung.overrideproperties.resolver.PropertySourceResolver; -@RunWith(SpringRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; + @SpringBootTest @ActiveProfiles("test") @EnableWebMvc diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java index a8c4267c5c..994a8a4288 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java @@ -12,6 +12,6 @@ public class PropertyOverrideContextInitializer implements ApplicationContextIni public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext, "example.firstProperty=" + PROPERTY_FIRST_VALUE); - TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "context-override-application.properties"); + TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "classpath:context-override-application.properties"); } } diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java index d00aa51e6c..bb08d701d9 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java @@ -1,16 +1,16 @@ package com.baeldung.overrideproperties; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.baeldung.overrideproperties.resolver.PropertySourceResolver; -@RunWith(SpringRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; + @SpringBootTest(properties = { "example.firstProperty=annotation" }) @EnableWebMvc public class SpringBootPropertySourceResolverIntegrationTest { @@ -23,8 +23,8 @@ public class SpringBootPropertySourceResolverIntegrationTest { final String firstProperty = propertySourceResolver.getFirstProperty(); final String secondProperty = propertySourceResolver.getSecondProperty(); - Assert.assertEquals("annotation", firstProperty); - Assert.assertEquals("file", secondProperty); + assertEquals("annotation", firstProperty); + assertEquals("file", secondProperty); } } \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java index dc15851277..673742124a 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java @@ -1,17 +1,16 @@ package com.baeldung.overrideproperties; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.baeldung.overrideproperties.resolver.PropertySourceResolver; -@RunWith(SpringRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; + @SpringBootTest @EnableWebMvc public class TestResourcePropertySourceResolverIntegrationTest { diff --git a/testing-modules/zerocode/README.md b/testing-modules/zerocode/README.md new file mode 100644 index 0000000000..a0a844c63d --- /dev/null +++ b/testing-modules/zerocode/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to ZeroCode](https://www.baeldung.com/zerocode-intro)