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-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-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-lang-4/README.md b/core-java-modules/core-java-lang-4/README.md new file mode 100644 index 0000000000..ff00688772 --- /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 + +- TODO 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/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/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/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..26d6a872d4 --- /dev/null +++ b/kubernetes/k8s-intro/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + + com.baeldung + kubernetes-parent + 1.0.0-SNAPSHOT + + k8s-intro + 0.0.1-SNAPSHOT + + + + io.kubernetes + client-java + 11.0.0 + + + + + + + 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/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/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/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/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-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/pom.xml b/pom.xml index 52ebabb727..5c75b19324 100644 --- a/pom.xml +++ b/pom.xml @@ -471,7 +471,7 @@ json-path jsoup jta - + kubernetes language-interop libraries-2 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-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