From b066bce2b621ec8317a93f81daee3340d667834b Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 6 Sep 2023 03:02:37 -0700 Subject: [PATCH 01/10] BAEL-6669, Passing Class Name as Parameter in Java --- .../createobject/basic/BronzeJobCard.java | 21 ++++++ .../createobject/basic/GoldJobCard.java | 17 +++++ .../createobject/basic/MaintenanceJob.java | 7 ++ .../createobject/basic/PaintJob.java | 7 ++ .../createobject/basic/RepairJob.java | 7 ++ .../createobject/basic/SilverJobCard.java | 22 ++++++ .../reflection/createobject/special/Job.java | 5 ++ .../createobject/special/MaintenanceJob.java | 7 ++ .../createobject/special/PaintJob.java | 8 +++ .../createobject/special/PlatinumJobCard.java | 16 +++++ .../createobject/special/RepairJob.java | 7 ++ .../src/main/resources/Bronze.puml | 20 ++++++ .../src/main/resources/Gold.puml | 20 ++++++ .../src/main/resources/Platinum.puml | 25 +++++++ .../src/main/resources/Silver.puml | 20 ++++++ .../CreateObjectBasicUnitTest.java | 67 +++++++++++++++++++ .../CreateObjectSpecialUnitTest.java | 29 ++++++++ 17 files changed, 305 insertions(+) create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/BronzeJobCard.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/GoldJobCard.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/MaintenanceJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/PaintJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/RepairJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/SilverJobCard.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/Job.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/MaintenanceJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PaintJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PlatinumJobCard.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/RepairJob.java create mode 100644 core-java-modules/core-java-reflection-2/src/main/resources/Bronze.puml create mode 100644 core-java-modules/core-java-reflection-2/src/main/resources/Gold.puml create mode 100644 core-java-modules/core-java-reflection-2/src/main/resources/Platinum.puml create mode 100644 core-java-modules/core-java-reflection-2/src/main/resources/Silver.puml create mode 100644 core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectBasicUnitTest.java create mode 100644 core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectSpecialUnitTest.java diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/BronzeJobCard.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/BronzeJobCard.java new file mode 100644 index 0000000000..cb8d7e8422 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/BronzeJobCard.java @@ -0,0 +1,21 @@ +package com.baeldung.reflection.createobject.basic; + +import java.lang.reflect.InvocationTargetException; + +public class BronzeJobCard { + private Object jobType; + public void setJobType(String jobType) throws ClassNotFoundException, + NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + Class jobTypeClass = Class.forName(jobType); + this.jobType = jobTypeClass.getDeclaredConstructor().newInstance(); + } + public String startJob() { + if(this.jobType instanceof RepairJob) { + return "Start Bronze " + ((RepairJob) this.jobType).getJobType(); + } + if(this.jobType instanceof MaintenanceJob) { + return "Start Bronze " + ((MaintenanceJob) this.jobType).getJobType(); + } + return "Bronze Job Failed"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/GoldJobCard.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/GoldJobCard.java new file mode 100644 index 0000000000..f6b14b9355 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/GoldJobCard.java @@ -0,0 +1,17 @@ +package com.baeldung.reflection.createobject.basic; + +import java.lang.reflect.InvocationTargetException; + +public class GoldJobCard { + private T jobType; + + public void setJobType(Class jobTypeClass) throws + NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + this.jobType = jobTypeClass.getDeclaredConstructor().newInstance(); + } + + public String startJob() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + return "Start Gold " + this.jobType.getClass().getMethod("getJobType") + .invoke(this.jobType).toString(); + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/MaintenanceJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/MaintenanceJob.java new file mode 100644 index 0000000000..8c268f0491 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/MaintenanceJob.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.createobject.basic; + +public class MaintenanceJob { + public String getJobType() { + return "Maintenance Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/PaintJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/PaintJob.java new file mode 100644 index 0000000000..74e6e2ccd2 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/PaintJob.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.createobject.basic; + +public class PaintJob { + public String getJobType() { + return "Paint Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/RepairJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/RepairJob.java new file mode 100644 index 0000000000..22fe8e3742 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/RepairJob.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.createobject.basic; + +public class RepairJob { + public String getJobType() { + return "Repair Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/SilverJobCard.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/SilverJobCard.java new file mode 100644 index 0000000000..231924bbaa --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/basic/SilverJobCard.java @@ -0,0 +1,22 @@ +package com.baeldung.reflection.createobject.basic; + +import java.lang.reflect.InvocationTargetException; + +public class SilverJobCard { + private Object jobType; + + public void setJobType(Class jobTypeClass) throws + NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + this.jobType = jobTypeClass.getDeclaredConstructor().newInstance(); + } + + public String startJob() { + if (this.jobType instanceof RepairJob) { + return "Start Silver " + ((RepairJob) this.jobType).getJobType(); + } + if (this.jobType instanceof MaintenanceJob) { + return "Start Silver " + ((MaintenanceJob) this.jobType).getJobType(); + } + return "Silver Job Failed"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/Job.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/Job.java new file mode 100644 index 0000000000..4fbf00e775 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/Job.java @@ -0,0 +1,5 @@ +package com.baeldung.reflection.createobject.special; + +public interface Job { + String getJobType(); +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/MaintenanceJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/MaintenanceJob.java new file mode 100644 index 0000000000..d93c20a09a --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/MaintenanceJob.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.createobject.special; + +public class MaintenanceJob implements Job { + public String getJobType() { + return "Maintenance Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PaintJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PaintJob.java new file mode 100644 index 0000000000..3eae7cb0c6 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PaintJob.java @@ -0,0 +1,8 @@ +package com.baeldung.reflection.createobject.special; + +public class PaintJob implements Job { + @Override + public String getJobType() { + return "Paint Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PlatinumJobCard.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PlatinumJobCard.java new file mode 100644 index 0000000000..4dd71e7fea --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/PlatinumJobCard.java @@ -0,0 +1,16 @@ +package com.baeldung.reflection.createobject.special; + +import java.lang.reflect.InvocationTargetException; + +public class PlatinumJobCard { + private T jobType; + + public void setJobType(Class jobTypeClass) throws + NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + this.jobType = jobTypeClass.getDeclaredConstructor().newInstance(); + } + + public String startJob() { + return "Start Platinum " + this.jobType.getJobType(); + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/RepairJob.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/RepairJob.java new file mode 100644 index 0000000000..985160fe48 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/createobject/special/RepairJob.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection.createobject.special; + +public class RepairJob implements Job { + public String getJobType() { + return "Repair Job"; + } +} diff --git a/core-java-modules/core-java-reflection-2/src/main/resources/Bronze.puml b/core-java-modules/core-java-reflection-2/src/main/resources/Bronze.puml new file mode 100644 index 0000000000..21f05fe52b --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/resources/Bronze.puml @@ -0,0 +1,20 @@ +@startuml +'https://plantuml.com/class-diagram + +class BronzeJobCard { + -Object jobType + +setJobType(String jobType) + +startJob() +} + +class MaintenanceJob { + +getJobType() +} +class RepairJob { + +getJobType() +} +BronzeJobCard -left-> MaintenanceJob:creates +BronzeJobCard -right-> RepairJob:creates + + +@enduml \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/main/resources/Gold.puml b/core-java-modules/core-java-reflection-2/src/main/resources/Gold.puml new file mode 100644 index 0000000000..2055154c21 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/resources/Gold.puml @@ -0,0 +1,20 @@ +@startuml +'https://plantuml.com/class-diagram + +class GoldJobCard { + -T jobType + +setJobType(Class jobTypeClass) + +startJob() +} + +class MaintenanceJob { + +getJobType() +} +class RepairJob { + +getJobType() +} +GoldJobCard -left-> MaintenanceJob:creates +GoldJobCard -right-> RepairJob:creates + + +@enduml \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/main/resources/Platinum.puml b/core-java-modules/core-java-reflection-2/src/main/resources/Platinum.puml new file mode 100644 index 0000000000..d9dc9b028d --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/resources/Platinum.puml @@ -0,0 +1,25 @@ +@startuml +'https://plantuml.com/class-diagram +interface Job { ++getJobType +} +class PlatinumJobCard { + +setJobType(Class jobTypeClass) + +startJob() +} + +class MaintenanceJob implements Job { + +getJobType() +} +class RepairJob implements Job { + +getJobType() +} +class PaintJob implements Job { + +getJobType() +} +PlatinumJobCard -up-> MaintenanceJob:creates +PlatinumJobCard -up-> RepairJob:creates +PlatinumJobCard -up-> PaintJob:creates + + +@enduml \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/main/resources/Silver.puml b/core-java-modules/core-java-reflection-2/src/main/resources/Silver.puml new file mode 100644 index 0000000000..46a9c88295 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/resources/Silver.puml @@ -0,0 +1,20 @@ +@startuml +'https://plantuml.com/class-diagram + +class SilverJobCard { + -Object jobType + +setJobType(Class jobTypeClass); + +startJob(); +} + +class MaintenanceJob { + +getJobType(); +} +class RepairJob { + +getJobType(); +} +SilverJobCard -left-> MaintenanceJob:creates +SilverJobCard -right-> RepairJob:creates + + +@enduml \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectBasicUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectBasicUnitTest.java new file mode 100644 index 0000000000..c8dcabf190 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectBasicUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.reflection.createobject; + +import com.baeldung.reflection.createobject.basic.*; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CreateObjectBasicUnitTest { + @Test + public void givenBronzeJobCard_whenJobTypeRepairAndMaintenance_thenStartJob() throws ClassNotFoundException, + InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + + BronzeJobCard bronzeJobCard1 = new BronzeJobCard(); + bronzeJobCard1.setJobType("com.baeldung.reflection.createobject.basic.RepairJob"); + assertEquals("Start Bronze Repair Job", bronzeJobCard1.startJob()); + + BronzeJobCard bronzeJobCard2 = new BronzeJobCard(); + bronzeJobCard2.setJobType("com.baeldung.reflection.createobject.basic.MaintenanceJob"); + assertEquals("Start Bronze Maintenance Job", bronzeJobCard2.startJob()); + } + @Test + public void givenBronzeJobCard_whenJobTypePaint_thenFailJob() throws ClassNotFoundException, + InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + + BronzeJobCard bronzeJobCard = new BronzeJobCard(); + bronzeJobCard.setJobType("com.baeldung.reflection.createobject.basic.PaintJob"); + assertEquals("Bronze Job Failed", bronzeJobCard.startJob()); + } + @Test + public void givenSilverJobCard_whenJobTypeRepairAndMaintenance_thenStartJob() throws InvocationTargetException, + NoSuchMethodException, InstantiationException, IllegalAccessException { + + SilverJobCard silverJobCard1 = new SilverJobCard(); + silverJobCard1.setJobType(RepairJob.class); + assertEquals("Start Silver Repair Job", silverJobCard1.startJob()); + + SilverJobCard silverJobCard2 = new SilverJobCard(); + silverJobCard2.setJobType(MaintenanceJob.class); + assertEquals("Start Silver Maintenance Job", silverJobCard2.startJob()); + } + @Test + public void givenSilverJobCard_whenJobTypePaint_thenFailJob() throws ClassNotFoundException, + InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + + SilverJobCard silverJobCard = new SilverJobCard(); + silverJobCard.setJobType(PaintJob.class); + assertEquals("Silver Job Failed", silverJobCard.startJob()); + } + @Test + public void givenGoldJobCard_whenJobTypeRepairMaintenanceAndPaint_thenStartJob() throws InvocationTargetException, + NoSuchMethodException, InstantiationException, IllegalAccessException { + + GoldJobCard goldJobCard1 = new GoldJobCard(); + goldJobCard1.setJobType(RepairJob.class); + assertEquals("Start Gold Repair Job", goldJobCard1.startJob()); + + GoldJobCard goldJobCard2 = new GoldJobCard(); + goldJobCard2.setJobType(MaintenanceJob.class); + assertEquals("Start Gold Maintenance Job", goldJobCard2.startJob()); + + GoldJobCard goldJobCard3 = new GoldJobCard(); + goldJobCard3.setJobType(PaintJob.class); + assertEquals("Start Gold Paint Job", goldJobCard3.startJob()); + } +} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectSpecialUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectSpecialUnitTest.java new file mode 100644 index 0000000000..99fdf7be2d --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/createobject/CreateObjectSpecialUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.reflection.createobject; + +import com.baeldung.reflection.createobject.special.MaintenanceJob; +import com.baeldung.reflection.createobject.special.PaintJob; +import com.baeldung.reflection.createobject.special.PlatinumJobCard; +import com.baeldung.reflection.createobject.special.RepairJob; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; + +public class CreateObjectSpecialUnitTest { + @Test + public void givenPlatinumJobCard_whenJobTypeRepairMaintenanceAndPaint_thenStartJob() throws InvocationTargetException, + NoSuchMethodException, InstantiationException, IllegalAccessException { + + PlatinumJobCard platinumJobCard1 = new PlatinumJobCard(); + platinumJobCard1.setJobType(RepairJob.class); + assertEquals("Start Platinum Repair Job", platinumJobCard1.startJob()); + + PlatinumJobCard platinumJobCard2 = new PlatinumJobCard(); + platinumJobCard2.setJobType(MaintenanceJob.class); + assertEquals("Start Platinum Maintenance Job", platinumJobCard2.startJob()); + + PlatinumJobCard platinumJobCard3 = new PlatinumJobCard(); + platinumJobCard3.setJobType(PaintJob.class); + assertEquals("Start Platinum Paint Job", platinumJobCard3.startJob()); + } +} From d0ed4ad157e72e7bd47d0b3d72e6938e9e6b2025 Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Tue, 12 Sep 2023 19:21:39 +0530 Subject: [PATCH 02/10] JAVA-20500: Changes made for Merge annotations module with google-auto-project --- google-auto-project/README.md | 2 + .../annotation-processing/pom.xml | 28 ++++ .../processor/BuilderProcessor.java | 123 ++++++++++++++++++ .../annotation/processor/BuilderProperty.java | 8 ++ .../src/main/resources/logback.xml | 13 ++ google-auto-project/annotation-user/pom.xml | 23 ++++ .../java/com/baeldung/annotation/Person.java | 29 +++++ .../src/main/resources/logback.xml | 13 ++ .../annotation/PersonBuilderUnitTest.java | 19 +++ google-auto-project/pom.xml | 7 + pom.xml | 2 - 11 files changed, 265 insertions(+), 2 deletions(-) create mode 100644 google-auto-project/annotation-processing/pom.xml create mode 100644 google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java create mode 100644 google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java create mode 100644 google-auto-project/annotation-processing/src/main/resources/logback.xml create mode 100644 google-auto-project/annotation-user/pom.xml create mode 100644 google-auto-project/annotation-user/src/main/java/com/baeldung/annotation/Person.java create mode 100644 google-auto-project/annotation-user/src/main/resources/logback.xml create mode 100644 google-auto-project/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java diff --git a/google-auto-project/README.md b/google-auto-project/README.md index d45a113a8f..44dd6c5d61 100644 --- a/google-auto-project/README.md +++ b/google-auto-project/README.md @@ -8,3 +8,5 @@ This module contains articles about automatic code generation - [Introduction to AutoFactory](https://www.baeldung.com/autofactory) - [Google AutoService](https://www.baeldung.com/google-autoservice) - [Defensive Copies for Collections Using AutoValue](https://www.baeldung.com/autovalue-defensive-copies) +- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder) + diff --git a/google-auto-project/annotation-processing/pom.xml b/google-auto-project/annotation-processing/pom.xml new file mode 100644 index 0000000000..5c872c2059 --- /dev/null +++ b/google-auto-project/annotation-processing/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + annotation-processing + annotation-processing + + + com.baeldung + google-auto-project + 1.0 + + + + + com.google.auto.service + auto-service + ${auto-service.version} + provided + + + + + 1.0-rc2 + + + \ No newline at end of file diff --git a/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java new file mode 100644 index 0000000000..18d8f9a8a9 --- /dev/null +++ b/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -0,0 +1,123 @@ +package com.baeldung.annotation.processor; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ExecutableType; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.google.auto.service.AutoService; + +@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") +@SupportedSourceVersion(SourceVersion.RELEASE_8) +@AutoService(Processor.class) +public class BuilderProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + + Map> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set"))); + + List setters = annotatedMethods.get(true); + List otherMethods = annotatedMethods.get(false); + + otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + + if (setters.isEmpty()) { + continue; + } + + String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); + + Map setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString())); + + try { + writeBuilderFile(className, setterMap); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return true; + } + + private void writeBuilderFile(String className, Map setterMap) throws IOException { + + String packageName = null; + int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + packageName = className.substring(0, lastDot); + } + + String simpleClassName = className.substring(lastDot + 1); + String builderClassName = className + "Builder"; + String builderSimpleClassName = builderClassName.substring(lastDot + 1); + + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); + try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { + + if (packageName != null) { + out.print("package "); + out.print(packageName); + out.println(";"); + out.println(); + } + + out.print("public class "); + out.print(builderSimpleClassName); + out.println(" {"); + out.println(); + + out.print(" private "); + out.print(simpleClassName); + out.print(" object = new "); + out.print(simpleClassName); + out.println("();"); + out.println(); + + out.print(" public "); + out.print(simpleClassName); + out.println(" build() {"); + out.println(" return object;"); + out.println(" }"); + out.println(); + + setterMap.entrySet().forEach(setter -> { + String methodName = setter.getKey(); + String argumentType = setter.getValue(); + + out.print(" public "); + out.print(builderSimpleClassName); + out.print(" "); + out.print(methodName); + + out.print("("); + + out.print(argumentType); + out.println(" value) {"); + out.print(" object."); + out.print(methodName); + out.println("(value);"); + out.println(" return this;"); + out.println(" }"); + out.println(); + }); + + out.println("}"); + + } + } + +} diff --git a/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java new file mode 100644 index 0000000000..84fcc73850 --- /dev/null +++ b/google-auto-project/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation.processor; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.SOURCE) +public @interface BuilderProperty { +} diff --git a/google-auto-project/annotation-processing/src/main/resources/logback.xml b/google-auto-project/annotation-processing/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/google-auto-project/annotation-processing/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/google-auto-project/annotation-user/pom.xml b/google-auto-project/annotation-user/pom.xml new file mode 100644 index 0000000000..c21a4ca03d --- /dev/null +++ b/google-auto-project/annotation-user/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + annotation-user + annotation-user + + + com.baeldung + google-auto-project + 1.0 + + + + + com.baeldung + annotation-processing + ${project.parent.version} + + + + \ No newline at end of file diff --git a/google-auto-project/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/google-auto-project/annotation-user/src/main/java/com/baeldung/annotation/Person.java new file mode 100644 index 0000000000..23787ba4f4 --- /dev/null +++ b/google-auto-project/annotation-user/src/main/java/com/baeldung/annotation/Person.java @@ -0,0 +1,29 @@ +package com.baeldung.annotation; + +import com.baeldung.annotation.processor.BuilderProperty; + +public class Person { + + private int age; + + private String name; + + public int getAge() { + return age; + } + + @BuilderProperty + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + @BuilderProperty + public void setName(String name) { + this.name = name; + } + +} diff --git a/google-auto-project/annotation-user/src/main/resources/logback.xml b/google-auto-project/annotation-user/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/google-auto-project/annotation-user/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/google-auto-project/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java b/google-auto-project/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java new file mode 100644 index 0000000000..d5f758089a --- /dev/null +++ b/google-auto-project/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.annotation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PersonBuilderUnitTest { + + @Test + public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { + + Person person = new PersonBuilder().setAge(25).setName("John").build(); + + assertEquals(25, person.getAge()); + assertEquals("John", person.getName()); + + } + +} diff --git a/google-auto-project/pom.xml b/google-auto-project/pom.xml index 839ccabc5f..034fea5aad 100644 --- a/google-auto-project/pom.xml +++ b/google-auto-project/pom.xml @@ -6,6 +6,8 @@ google-auto-project 1.0 google-auto-project + pom + com.baeldung @@ -13,6 +15,11 @@ 1.0.0-SNAPSHOT + + annotation-processing + annotation-user + + com.google.auto.value diff --git a/pom.xml b/pom.xml index 1618ac684f..87308ff0bd 100644 --- a/pom.xml +++ b/pom.xml @@ -812,7 +812,6 @@ akka-modules - annotations httpclient-simple antlr apache-kafka @@ -1086,7 +1085,6 @@ akka-modules - annotations antlr apache-kafka apache-kafka-2 From 77270f8418105cd7e3971b72b7a86b31c85af13b Mon Sep 17 00:00:00 2001 From: Bipinkumar27 Date: Tue, 12 Sep 2023 19:22:23 +0530 Subject: [PATCH 03/10] JAVA-20500: Changes made for Merge annotations module with google-auto-project(removing annotations module) --- annotations/README.md | 7 - annotations/annotation-processing/pom.xml | 28 ---- .../processor/BuilderProcessor.java | 123 ------------------ .../annotation/processor/BuilderProperty.java | 8 -- .../src/main/resources/logback.xml | 13 -- annotations/annotation-user/pom.xml | 23 ---- .../java/com/baeldung/annotation/Person.java | 29 ----- .../src/main/resources/logback.xml | 13 -- .../annotation/PersonBuilderUnitTest.java | 19 --- annotations/pom.xml | 21 --- 10 files changed, 284 deletions(-) delete mode 100644 annotations/README.md delete mode 100644 annotations/annotation-processing/pom.xml delete mode 100644 annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java delete mode 100644 annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java delete mode 100644 annotations/annotation-processing/src/main/resources/logback.xml delete mode 100644 annotations/annotation-user/pom.xml delete mode 100644 annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java delete mode 100644 annotations/annotation-user/src/main/resources/logback.xml delete mode 100644 annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java delete mode 100644 annotations/pom.xml diff --git a/annotations/README.md b/annotations/README.md deleted file mode 100644 index ec4005fc5e..0000000000 --- a/annotations/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Annotations - -This module contains articles about Java annotations - -### Relevant Articles: - -- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder) diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml deleted file mode 100644 index 14bbc409e5..0000000000 --- a/annotations/annotation-processing/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - annotation-processing - annotation-processing - - - com.baeldung - 1.0.0-SNAPSHOT - annotations - - - - - com.google.auto.service - auto-service - ${auto-service.version} - provided - - - - - 1.0-rc2 - - - \ No newline at end of file diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java deleted file mode 100644 index 18d8f9a8a9..0000000000 --- a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.baeldung.annotation.processor; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.processing.*; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.Element; -import javax.lang.model.element.TypeElement; -import javax.lang.model.type.ExecutableType; -import javax.tools.Diagnostic; -import javax.tools.JavaFileObject; - -import com.google.auto.service.AutoService; - -@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") -@SupportedSourceVersion(SourceVersion.RELEASE_8) -@AutoService(Processor.class) -public class BuilderProcessor extends AbstractProcessor { - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - for (TypeElement annotation : annotations) { - - Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); - - Map> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set"))); - - List setters = annotatedMethods.get(true); - List otherMethods = annotatedMethods.get(false); - - otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element)); - - if (setters.isEmpty()) { - continue; - } - - String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); - - Map setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString())); - - try { - writeBuilderFile(className, setterMap); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - return true; - } - - private void writeBuilderFile(String className, Map setterMap) throws IOException { - - String packageName = null; - int lastDot = className.lastIndexOf('.'); - if (lastDot > 0) { - packageName = className.substring(0, lastDot); - } - - String simpleClassName = className.substring(lastDot + 1); - String builderClassName = className + "Builder"; - String builderSimpleClassName = builderClassName.substring(lastDot + 1); - - JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); - try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { - - if (packageName != null) { - out.print("package "); - out.print(packageName); - out.println(";"); - out.println(); - } - - out.print("public class "); - out.print(builderSimpleClassName); - out.println(" {"); - out.println(); - - out.print(" private "); - out.print(simpleClassName); - out.print(" object = new "); - out.print(simpleClassName); - out.println("();"); - out.println(); - - out.print(" public "); - out.print(simpleClassName); - out.println(" build() {"); - out.println(" return object;"); - out.println(" }"); - out.println(); - - setterMap.entrySet().forEach(setter -> { - String methodName = setter.getKey(); - String argumentType = setter.getValue(); - - out.print(" public "); - out.print(builderSimpleClassName); - out.print(" "); - out.print(methodName); - - out.print("("); - - out.print(argumentType); - out.println(" value) {"); - out.print(" object."); - out.print(methodName); - out.println("(value);"); - out.println(" return this;"); - out.println(" }"); - out.println(); - }); - - out.println("}"); - - } - } - -} diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java deleted file mode 100644 index 84fcc73850..0000000000 --- a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.annotation.processor; - -import java.lang.annotation.*; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.SOURCE) -public @interface BuilderProperty { -} diff --git a/annotations/annotation-processing/src/main/resources/logback.xml b/annotations/annotation-processing/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/annotations/annotation-processing/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml deleted file mode 100644 index 37a2e36f61..0000000000 --- a/annotations/annotation-user/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - annotation-user - annotation-user - - - com.baeldung - annotations - 1.0.0-SNAPSHOT - - - - - com.baeldung - annotation-processing - ${project.parent.version} - - - - \ No newline at end of file diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java deleted file mode 100644 index 23787ba4f4..0000000000 --- a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.annotation; - -import com.baeldung.annotation.processor.BuilderProperty; - -public class Person { - - private int age; - - private String name; - - public int getAge() { - return age; - } - - @BuilderProperty - public void setAge(int age) { - this.age = age; - } - - public String getName() { - return name; - } - - @BuilderProperty - public void setName(String name) { - this.name = name; - } - -} diff --git a/annotations/annotation-user/src/main/resources/logback.xml b/annotations/annotation-user/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/annotations/annotation-user/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java deleted file mode 100644 index d5f758089a..0000000000 --- a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.annotation; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class PersonBuilderUnitTest { - - @Test - public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { - - Person person = new PersonBuilder().setAge(25).setName("John").build(); - - assertEquals(25, person.getAge()); - assertEquals("John", person.getName()); - - } - -} diff --git a/annotations/pom.xml b/annotations/pom.xml deleted file mode 100644 index b3fabb8637..0000000000 --- a/annotations/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - annotations - annotations - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - annotation-processing - annotation-user - - - \ No newline at end of file From 9bec8ebcdb645626a43ab883130450fdd4c8b18e Mon Sep 17 00:00:00 2001 From: vunamtien Date: Wed, 13 Sep 2023 02:58:56 +0700 Subject: [PATCH 04/10] BAEL-6816-create-stream-regex-matches (#14731) * BAEL-6816-create-stream-regex-matches * add unit test --------- Co-authored-by: tienvn --- .../regexmatches/StreamFromRegexUtil.java | 16 +++++++++++ .../regexmatches/StreamFromRegexUnitTest.java | 27 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/regexmatches/StreamFromRegexUtil.java create mode 100644 core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/regexmatches/StreamFromRegexUnitTest.java diff --git a/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/regexmatches/StreamFromRegexUtil.java b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/regexmatches/StreamFromRegexUtil.java new file mode 100644 index 0000000000..f7187c79de --- /dev/null +++ b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/regexmatches/StreamFromRegexUtil.java @@ -0,0 +1,16 @@ +package com.baeldung.streams.regexmatches; + +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +public class StreamFromRegexUtil { + + public static Stream getStream(String input, String regex) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(input); + return matcher.results().map(MatchResult::group); + } + +} diff --git a/core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/regexmatches/StreamFromRegexUnitTest.java b/core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/regexmatches/StreamFromRegexUnitTest.java new file mode 100644 index 0000000000..9d8b840e0e --- /dev/null +++ b/core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/regexmatches/StreamFromRegexUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.streams.regexmatches; + +import org.junit.Test; + +import java.util.List; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertEquals; + +public class StreamFromRegexUnitTest { + + @Test + public void whenInputStringIncludeLettersAndNumbersAndRegex_ThenReturnStreamOfNumbers() { + List result = StreamFromRegexUtil.getStream("There are 3 apples and 2 bananas on the table.", "\\d+") + .collect(Collectors.toList()); + assertEquals(asList("3", "2"), result); + } + + @Test + public void whenInputStringsAndRegex_ThenReturnStreamOfJavaWords() { + List result = StreamFromRegexUtil.getStream("sample sentence with some words Java Java", "\\bJava\\b") + .collect(Collectors.toList()); + assertEquals(asList("Java", "Java"), result); + } + +} From 7c02a6ffdbc43d35c639c518ddb8faaef533a5a3 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 12 Sep 2023 23:46:08 +0200 Subject: [PATCH 05/10] [integer-to-digits] How to Split an Integer Number Into Digits in Java (#14736) --- .../IntegerToDigitsUnitTest.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertodigits/IntegerToDigitsUnitTest.java diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertodigits/IntegerToDigitsUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertodigits/IntegerToDigitsUnitTest.java new file mode 100644 index 0000000000..3162fba814 --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertodigits/IntegerToDigitsUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.integertodigits; + +import com.google.common.collect.Lists; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class IntegerToDigitsUnitTest { + private final static int THE_NUMBER = 1230456; + private final static List EXPECTED_INT_LIST = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6); + private final static String[] EXPECTED_STR_ARRAY = new String[] { "1", "2", "3", "0", "4", "5", "6" }; + private final static List EXPECTED_STR_LIST = Lists.newArrayList("1", "2", "3", "0", "4", "5", "6"); + private final static char[] EXPECTED_CHAR_ARRAY = new char[] { '1', '2', '3', '0', '4', '5', '6' }; + + @Test + void whenUsingModOperator_thenGetExpectedResult() { + int number = THE_NUMBER; + LinkedList result = new LinkedList<>(); + while (number > 0) { + result.push(number % 10); + number /= 10; + } + assertEquals(EXPECTED_INT_LIST, result); + } + + + private void collectDigits(int num, List digitList) { + if (num / 10 > 0) { + collectDigits(num / 10, digitList); + } + digitList.add(num % 10); + } + + @Test + void whenUsingModOperatorAndRecursion_thenGetExpectedResult() { + List result = new ArrayList<>(); + collectDigits(THE_NUMBER, result); + assertEquals(EXPECTED_INT_LIST, result); + } + + @Test + void whenUsingIntStream_thenGetExpectedResult() { + String numStr = String.valueOf(THE_NUMBER); + List result = numStr.chars().map(Character::getNumericValue).boxed().collect(Collectors.toList()); + assertEquals(EXPECTED_INT_LIST, result); + } + + @Test + void whenUsingToCharArray_thenGetExpectedResult() { + String numStr = String.valueOf(THE_NUMBER); + char[] result = numStr.toCharArray(); + assertArrayEquals(EXPECTED_CHAR_ARRAY, result); + } + + @Test + void whenUsingSplit_thenGetExpectedResult() { + String numStr = String.valueOf(THE_NUMBER); + String[] result = numStr.split("(?<=.)"); + assertArrayEquals(EXPECTED_STR_ARRAY, result); + } +} \ No newline at end of file From cc911cefeb6193a8b9123e03d5923902a3042812 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Wed, 13 Sep 2023 01:18:47 +0000 Subject: [PATCH 06/10] Differences between Heap Dump, thread dump and core dump (#14718) * Differences between Heap Dump, thread dump and core dump * Differences between Heap Dump, thread dump and core dump * Differences between Heap Dump, thread dump and core dump * Differences Between Heap Dump, Thread Dump and Core Dump --- .../main/java/com/baeldung/dumps/CoreDump.c | 15 +++++++++++++ .../main/java/com/baeldung/dumps/CoreDump.h | 21 +++++++++++++++++++ .../java/com/baeldung/dumps/CoreDump.java | 13 ++++++++++++ .../java/com/baeldung/dumps/HeapDump.java | 19 +++++++++++++++++ .../java/com/baeldung/dumps/ThreadDump.java | 18 ++++++++++++++++ 5 files changed, 86 insertions(+) create mode 100644 core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.c create mode 100644 core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.h create mode 100644 core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.java create mode 100644 core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/HeapDump.java create mode 100644 core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/ThreadDump.java diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.c b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.c new file mode 100644 index 0000000000..4a8b2c2b83 --- /dev/null +++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.c @@ -0,0 +1,15 @@ +#include +#include "CoreDump.h" + +void core() { + int *p = NULL; + *p = 0; +} + +JNIEXPORT void JNICALL Java_CoreDump_core (JNIEnv *env, jobject obj) { + core(); +}; + +void main() { +} + diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.h b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.h new file mode 100644 index 0000000000..3b0e34b77d --- /dev/null +++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class CoreDump */ + +#ifndef _Included_CoreDump +#define _Included_CoreDump +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: CoreDump + * Method: core + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_CoreDump_core + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.java new file mode 100644 index 0000000000..17725ee567 --- /dev/null +++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/CoreDump.java @@ -0,0 +1,13 @@ +package com.baeldung.dumps; + +public class CoreDump { + static { + System.loadLibrary("nativelib"); + } + + public static void main(String[] args) { + new CoreDump().core(); + } + + private native void core(); +} diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/HeapDump.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/HeapDump.java new file mode 100644 index 0000000000..c117c4f9a9 --- /dev/null +++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/HeapDump.java @@ -0,0 +1,19 @@ +package com.baeldung.dumps; + +import java.util.ArrayList; +import java.util.List; + +public class HeapDump { + public static void main(String[] args) { + List numbers = new ArrayList<>(); + + try { + while (true) { + numbers.add(10); + } + } catch (OutOfMemoryError e) { + System.out.println("Out of memory error occurred!"); + } + } + +} diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/ThreadDump.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/ThreadDump.java new file mode 100644 index 0000000000..1d76c911de --- /dev/null +++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/dumps/ThreadDump.java @@ -0,0 +1,18 @@ +package com.baeldung.dumps; + +public class ThreadDump { + public static void main(String[] args) { + longRunningTask(); + } + + private static void longRunningTask() { + for (int i = 0; i < Integer.MAX_VALUE; i++) { + if (Thread.currentThread().isInterrupted()) { + System.out.println("Interrupted!"); + break; + } + System.out.println(i); + } + } + +} From e53995fc81d0b7435667e04a07f9afdad87e9c1e Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 13 Sep 2023 14:51:55 +0530 Subject: [PATCH 07/10] JAVA-24547: Fixes made for adding spring-data-jpa-repo-3 (#14735) --- persistence-modules/pom.xml | 2 +- persistence-modules/spring-data-jpa-repo-3/pom.xml | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index e2d6ef67f3..ec02b0f37c 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -117,7 +117,7 @@ rethinkdb scylladb spring-data-cassandra-2 - + spring-data-jpa-repo-3 diff --git a/persistence-modules/spring-data-jpa-repo-3/pom.xml b/persistence-modules/spring-data-jpa-repo-3/pom.xml index 207e753ecd..211e8a2d96 100644 --- a/persistence-modules/spring-data-jpa-repo-3/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-3/pom.xml @@ -32,5 +32,8 @@ test + + com.baeldung.spring.data.jpa.naturalid.Application + From 76f7964c96c582c4629dd530cc08cbe5466e97dc Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 13 Sep 2023 14:58:47 +0530 Subject: [PATCH 08/10] JAVA-24677: Changes made for add sub-modules in parents (#14690) --- core-java-modules/core-java-9-improvements/pom.xml | 2 +- core-java-modules/core-java-9-jigsaw/library-core/pom.xml | 4 ++-- core-java-modules/core-java-9-jigsaw/pom.xml | 7 +++---- core-java-modules/pom.xml | 1 + java-panama/pom.xml | 4 ++-- pom.xml | 5 +++++ spring-boot-modules/pom.xml | 1 + spring-boot-modules/spring-boot-3-url-matching/pom.xml | 2 +- 8 files changed, 16 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml index f6f13ff409..ce40a4acb8 100644 --- a/core-java-modules/core-java-9-improvements/pom.xml +++ b/core-java-modules/core-java-9-improvements/pom.xml @@ -10,7 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../../ + ../../pom.xml diff --git a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml index 80638367cf..415c7fb053 100644 --- a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml +++ b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung + com.baeldung.core-java-modules core-java-9-jigsaw - 0.2-SNAPSHOT + 0.0.1-SNAPSHOT library-core diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml index 288254b9cf..4afe2ae31a 100644 --- a/core-java-modules/core-java-9-jigsaw/pom.xml +++ b/core-java-modules/core-java-9-jigsaw/pom.xml @@ -11,10 +11,9 @@ - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 0fc950697f..9cc42ce5d2 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -176,6 +176,7 @@ core-java-uuid core-java-collections-maps-6 core-java-records + core-java-9-jigsaw diff --git a/java-panama/pom.xml b/java-panama/pom.xml index 7c6b420eeb..18dffaec73 100644 --- a/java-panama/pom.xml +++ b/java-panama/pom.xml @@ -1,10 +1,10 @@ - ${project.model.version} + 4.0.0 com.baeldung.java.panama java-panama - ${project.version} + 1.0 java-panama jar diff --git a/pom.xml b/pom.xml index 1618ac684f..fc12db6ed8 100644 --- a/pom.xml +++ b/pom.xml @@ -543,6 +543,7 @@ persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive java-nashorn + jeromq spring-ejb-modules/ejb-beans @@ -939,6 +940,7 @@ gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j parent-boot-3 + @@ -1213,6 +1215,9 @@ language-interop gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j + spring-actuator + spring-cloud-modules/spring-cloud-azure + spring-cloud-modules/spring-cloud-contract diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 20698169af..1c4b2bb38f 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -103,6 +103,7 @@ spring-boot-mvc-legacy spring-boot-springdoc-2 spring-boot-documentation + spring-boot-3-url-matching diff --git a/spring-boot-modules/spring-boot-3-url-matching/pom.xml b/spring-boot-modules/spring-boot-3-url-matching/pom.xml index aa83a676d7..43f89eab47 100644 --- a/spring-boot-modules/spring-boot-3-url-matching/pom.xml +++ b/spring-boot-modules/spring-boot-3-url-matching/pom.xml @@ -67,7 +67,7 @@ io.projectreactor reactor-test - ${reactor-test.version} + ${reactor-core.version} test From d1675453257468f16339510d1dd5c6b9a8a3b838 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 13 Sep 2023 12:39:35 +0300 Subject: [PATCH 09/10] [JAVA-20157] Upgraded core-java-serialization module to JDK17 (#14646) * [JAVA-20157] Upgraded core-java-serialization module to JDK17 * [JAVA-20157] Upgraded core-java-nio-2 module to JDK17 --- core-java-modules/core-java-nio-2/pom.xml | 14 ++++++++++++++ core-java-modules/core-java-serialization/pom.xml | 6 ++++++ core-java-modules/pom.xml | 4 ++-- pom.xml | 4 ---- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml index e35b70cfc7..dde708c10d 100644 --- a/core-java-modules/core-java-nio-2/pom.xml +++ b/core-java-modules/core-java-nio-2/pom.xml @@ -13,4 +13,18 @@ 0.0.1-SNAPSHOT + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.nio=ALL-UNNAMED + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml index 5a6f256687..63771d2da0 100644 --- a/core-java-modules/core-java-serialization/pom.xml +++ b/core-java-modules/core-java-serialization/pom.xml @@ -53,6 +53,12 @@ ${spring.core.version} test + + org.projectlombok + lombok + ${lombok.version} + provided + diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 9cc42ce5d2..e9285eaf1e 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -24,9 +24,7 @@ - - core-java-9-improvements @@ -143,6 +141,7 @@ core-java-networking-2 core-java-networking-4 core-java-nio + core-java-nio-2 core-java-numbers core-java-numbers-2 core-java-numbers-3 @@ -159,6 +158,7 @@ core-java-security-3 core-java-security-4 core-java-security-algorithms + core-java-serialization core-java-streams core-java-streams-3 core-java-string-algorithms diff --git a/pom.xml b/pom.xml index c39ae51629..cb794fe211 100644 --- a/pom.xml +++ b/pom.xml @@ -342,8 +342,6 @@ core-java-modules/core-java-8-datetime-2 core-java-modules/core-java-sun core-java-modules/core-java-security - core-java-modules/core-java-nio-2 - core-java-modules/core-java-serialization core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 @@ -519,8 +517,6 @@ core-java-modules/core-java-8-datetime-2 core-java-modules/core-java-sun core-java-modules/core-java-security - core-java-modules/core-java-nio-2 - core-java-modules/core-java-serialization core-java-modules/core-java-lang core-java-modules/core-java-lang-math-3 From ac590b3823ee9e98a7a0b13023e214beb4f88916 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 13 Sep 2023 13:16:19 +0300 Subject: [PATCH 10/10] JAVA-17488 (#14694) Moved remaining apache-httpclient v4 code from apache-httpclient to apache-httpclient4 --- .../ApacheHttpClient5UnitTest.java | 2 +- .../HttpClientUnitTest.java | 7 +- .../HttpUrlConnectionUnitTest.java | 10 ++- .../SpringRestTemplateUnitTest.java | 2 +- .../SpringWebClientUnitTest.java | 4 +- apache-httpclient/pom.xml | 43 ---------- .../HttpClientMultipartLiveTest.java | 6 +- .../HttpClientRedirectLiveTest.java | 9 ++- ...tAdvancedConfigurationIntegrationTest.java | 45 +++++++---- .../base/HttpClientBasicPostLiveTest.java | 59 -------------- .../httpclient/base/HttpClientLiveTest.java | 75 ------------------ ...ttpClientConnectionManagementLiveTest.java | 36 ++++----- .../conn/IdleConnectionMonitorThread.java | 41 ---------- .../conn/MultiHttpClientConnThread.java | 1 - .../client}/HttpClientSandboxLiveTest.java | 13 +-- .../client/RestClientV4LiveManualTest.java | 4 +- .../com/baeldung/httpclient/ClientUtil.java | 2 - .../httpclient/HttpAsyncClientV4LiveTest.java | 1 + .../HttpClientCancelRequestV4LiveTest.java | 14 ++-- .../HttpClientCookBookV4LiveTest.java | 20 +++++ .../HttpClientRedirectV4LiveTest.java | 6 +- .../HttpClientTimeoutV4LiveTest.java | 20 +++++ ...tAdvancedConfigurationIntegrationTest.java | 48 ++++++----- .../HttpClientExpandUrlLiveTest.java | 17 ++-- .../httpclient/ApacheHttpClientUnitTest.java | 1 - ...ttpClientConnectionManagementLiveTest.java | 79 ++++++++++--------- .../conn/MultiHttpClientConnThread.java | 1 - ...sterVersion_MultiHttpClientConnThread.java | 1 - .../ApacheHttpClientUnitTest.java | 7 +- .../retry/ApacheHttpClientRetryLiveTest.java | 18 ++--- 30 files changed, 220 insertions(+), 372 deletions(-) delete mode 100644 apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java delete mode 100644 apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java delete mode 100644 apache-httpclient/src/test/java/com/baeldung/httpclient/conn/IdleConnectionMonitorThread.java rename {apache-httpclient/src/test/java/com/baeldung/httpclient/base => apache-httpclient4/src/test/java/com/baeldung/client}/HttpClientSandboxLiveTest.java (82%) diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java index 9a79cbf491..8bf1278c3e 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClient5UnitTest.java @@ -16,7 +16,7 @@ public class ApacheHttpClient5UnitTest { public static final String DUMMY_URL = "https://postman-echo.com/get"; @Test - public void whenUseApacheHttpClient_thenCorrect() throws IOException { + void whenUseApacheHttpClient_thenCorrect() throws IOException { HttpGet request = new HttpGet(DUMMY_URL); try (CloseableHttpClient client = HttpClients.createDefault()) { diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java index 1dca1bf7c6..dcd3e38371 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpClientUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.httpclient.readresponsebodystring; -import org.junit.Test; import java.io.IOException; import java.net.URI; @@ -8,11 +7,13 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -public class HttpClientUnitTest { +import org.junit.jupiter.api.Test; + +class HttpClientUnitTest { public static final String DUMMY_URL = "https://postman-echo.com/get"; @Test - public void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException { + void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build(); diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java index 54ae887eb4..e19fbd6c53 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/HttpUrlConnectionUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.httpclient.readresponsebodystring; -import org.junit.Assert; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.BufferedReader; import java.io.IOException; @@ -10,12 +10,14 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; +import org.junit.jupiter.api.Test; + public class HttpUrlConnectionUnitTest { public static final String DUMMY_URL = "https://postman-echo.com/get"; @Test - public void whenUseHttpUrlConnection_thenCorrect() throws IOException { + void whenUseHttpUrlConnection_thenCorrect() throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection(); InputStream inputStream = connection.getInputStream(); @@ -28,7 +30,7 @@ public class HttpUrlConnectionUnitTest { response.append(currentLine); in.close(); - Assert.assertNotNull(response.toString()); + assertNotNull(response.toString()); System.out.println("Response -> " + response.toString()); } } diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java index c59d7662f1..e06cc165f0 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringRestTemplateUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.httpclient.readresponsebodystring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.web.client.RestTemplate; public class SpringRestTemplateUnitTest { diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java index 9bd2f825ad..df71bab983 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/SpringWebClientUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.httpclient.readresponsebodystring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @@ -8,7 +8,7 @@ public class SpringWebClientUnitTest { public static final String DUMMY_URL = "https://postman-echo.com/get"; @Test - public void whenUseWebClientRetrieve_thenCorrect() { + void whenUseWebClientRetrieve_thenCorrect() { WebClient webClient = WebClient.create(DUMMY_URL); Mono body = webClient.get().retrieve().bodyToMono(String.class); String s = body.block(); diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index 5c3ea5b3b3..1b22d64799 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -15,45 +15,6 @@ - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - fluent-hc - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - httpmime - ${httpclient.version} - - - org.apache.httpcomponents - httpasyncclient - ${httpasyncclient.version} - - - commons-logging - commons-logging - - - org.apache.httpcomponents.core5 httpcore5 @@ -115,12 +76,8 @@ - - 4.1.4 - 5.6.1 2.5.1 - 4.5.8 5.2 5.2 diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java index 69eedc8e48..627ac2bd31 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -4,10 +4,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.apache.hc.core5.http.ParseException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.entity.mime.FileBody; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; @@ -19,6 +19,7 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.ParseException; import java.io.BufferedReader; import java.io.File; @@ -30,9 +31,6 @@ import java.net.URL; class HttpClientMultipartLiveTest extends GetRequestMockServer { - // No longer available - // private static final String SERVER = "http://echo.200please.com"; - private static final String SERVER = "http://localhost:8080/spring-mvc-java/stub/multipart"; private static final String TEXTFILENAME = "temp.txt"; private static final String IMAGEFILENAME = "image.jpg"; diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java index 04fad84333..560eb0c8ef 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientRedirectLiveTest.java @@ -1,15 +1,16 @@ package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import org.junit.jupiter.api.Test; + import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClients; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import java.io.IOException; diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index 3f2c1328e8..3ac3ee88be 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -8,7 +8,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -29,21 +29,34 @@ import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.io.entity.StringEntity; -import org.junit.Rule; -import org.junit.Test; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class HttpClientAdvancedConfigurationIntegrationTest { +import com.github.tomakehurst.wiremock.WireMockServer; - @Rule - public WireMockRule serviceMock = new WireMockRule(8089); +class HttpClientAdvancedConfigurationIntegrationTest { - @Rule - public WireMockRule proxyMock = new WireMockRule(8090); + public WireMockServer serviceMock; + public WireMockServer proxyMock; + + @BeforeEach + public void before () { + serviceMock = new WireMockServer(8089); + serviceMock.start(); + proxyMock = new WireMockServer(8090); + proxyMock.start(); + } + + @AfterEach + public void after () { + serviceMock.stop(); + proxyMock.stop(); + } @Test - public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { + void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { //given String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) @@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpGet); //then - assertEquals(response.getCode(), 200); + assertEquals(200, response.getCode()); } @Test - public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { + void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { //given String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) @@ -82,12 +95,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpPost); //then - assertEquals(response.getCode(), 200); + assertEquals(200, response.getCode()); } @Test - public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { + void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { //given proxyMock.stubFor(get(urlMatching(".*")) .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); @@ -107,7 +120,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpclient.execute(httpGet); //then - assertEquals(response.getCode(), 200); + assertEquals(200, response.getCode()); proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } @@ -151,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpclient.execute(httpGet, context); //then - assertEquals(response.getCode(), 200); + assertEquals(200, response.getCode()); proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java deleted file mode 100644 index 9d4573084b..0000000000 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.httpclient.base; - -import com.baeldung.httpclient.ResponseUtil; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -public class HttpClientBasicPostLiveTest { - - private static final String SAMPLE_URL = "http://www.github.com"; - - private CloseableHttpClient instance; - - private CloseableHttpResponse response; - - @Before - public final void before() { - instance = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests - non-GET - - @Test - public final void whenExecutingPostRequest_thenNoExceptions() throws IOException { - instance.execute(new HttpPost(SAMPLE_URL)); - } - - @Test - public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { - final HttpPost request = new HttpPost(SAMPLE_URL); - request.setEntity(new StringEntity("in the body of the POST")); - instance.execute(request); - } - - @Test - public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { - final HttpPost request = new HttpPost(SAMPLE_URL); - request.setEntity(new StringEntity("in the body of the POST")); - final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); - request.addHeader(new BasicScheme().authenticate(creds, request, null)); - instance.execute(request); - } - -} diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java deleted file mode 100644 index b8bc536918..0000000000 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.httpclient.base; - -import com.baeldung.httpclient.ResponseUtil; - -import org.apache.http.Header; -import org.apache.http.HttpHeaders; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class HttpClientLiveTest { - - private static final String SAMPLE_URL = "http://www.github.com"; - - private CloseableHttpClient instance; - - private CloseableHttpResponse response; - - @Before - public final void before() { - instance = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests - - @Test(expected = ConnectTimeoutException.class) - public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { - final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build(); - final HttpGet request = new HttpGet(SAMPLE_URL); - request.setConfig(requestConfig); - response = instance.execute(request); - } - - // tests - configs - - @Test - public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException { - instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build(); - response = instance.execute(new HttpGet(SAMPLE_URL)); - } - - @Test - public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException { - final HttpGet request = new HttpGet(SAMPLE_URL); - request.addHeader(HttpHeaders.ACCEPT, "application/xml"); - response = instance.execute(request); - } - - @Test - public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException { - response = instance.execute(new HttpGet(SAMPLE_URL)); - - final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); - assertThat(headers, not(emptyArray())); - } - -} diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index 9d5294aa7e..b0c60c0ab1 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -1,5 +1,6 @@ package com.baeldung.httpclient.conn; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -34,14 +35,13 @@ import org.apache.hc.core5.pool.PoolStats; import org.apache.hc.core5.util.Args; import org.apache.hc.core5.util.TimeValue; import org.apache.hc.core5.util.Timeout; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HttpClientConnectionManagementLiveTest { +class HttpClientConnectionManagementLiveTest { // Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection) @Test - public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException { + final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException { BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager(); HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443)); final LeaseRequest connRequest = connMgr.lease("some-id", route, null); @@ -51,7 +51,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient @Test - public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException { + final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException { PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(poolingConnManager) @@ -65,7 +65,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 3.2. Using Two HttpClients to Connect to One Target Host Each @Test - public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException { + final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException { HttpGet get1 = new HttpGet("https://www.baeldung.com"); HttpGet get2 = new HttpGet("https://www.google.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); @@ -83,8 +83,7 @@ public class HttpClientConnectionManagementLiveTest { thread1.join(); thread2.join(); - Assert.assertTrue(connManager.getTotalStats() - .getLeased() == 0); + assertEquals(0, connManager.getTotalStats().getLeased()); client1.close(); client2.close(); connManager.close(); @@ -92,7 +91,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits @Test - public final void whenIncreasingConnectionPool_thenNoExceptions() { + final void whenIncreasingConnectionPool_thenNoExceptions() { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(5); connManager.setDefaultMaxPerRoute(4); @@ -103,7 +102,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 4.2. Using Threads to Execute Connections @Test - public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException { + final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException { HttpGet get = new HttpGet("http://www.baeldung.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() @@ -133,7 +132,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 5.1. A Custom Keep Alive Strategy @Test - public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() { + final void whenCustomizingKeepAliveStrategy_thenNoExceptions() { final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @Override public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) { @@ -162,7 +161,7 @@ public class HttpClientConnectionManagementLiveTest { //Example 6.1. BasicHttpClientConnectionManager Connection Reuse @Test - public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException { + final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException { BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager(); HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443)); final HttpContext context = new BasicHttpContext(); @@ -184,7 +183,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads @Test - public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException { + final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException { HttpGet get = new HttpGet("http://www.baeldung.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(6); @@ -208,7 +207,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 7.1. Setting Socket Timeout to 5 Seconds @Test - public final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException { + final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException { final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80)); final HttpContext context = new BasicHttpContext(); final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); @@ -227,7 +226,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 8.1. Setting the HttpClient to Check for Stale Connections @Test - public final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException { + final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException { final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(100); try (final CloseableHttpClient httpclient = HttpClients.custom() @@ -266,7 +265,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 9.1. Closing Connection and Releasing Resources @Test - public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws IOException { + final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(connManager) @@ -282,7 +281,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // Example 3.2. TESTER VERSION - public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException { + final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException { HttpGet get1 = new HttpGet("https://www.baeldung.com"); HttpGet get2 = new HttpGet("https://www.google.com"); @@ -300,8 +299,7 @@ public class HttpClientConnectionManagementLiveTest { thread2.start(); thread1.join(); thread2.join(1000); - Assert.assertTrue(poolingConnManager.getTotalStats() - .getLeased() == 2); + assertEquals(2, poolingConnManager.getTotalStats().getLeased()); client1.close(); client2.close(); diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/IdleConnectionMonitorThread.java deleted file mode 100644 index f1d7cbc427..0000000000 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/IdleConnectionMonitorThread.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.httpclient.conn; - -import java.util.concurrent.TimeUnit; - -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - -public class IdleConnectionMonitorThread extends Thread { - private final HttpClientConnectionManager connMgr; - private volatile boolean shutdown; - - IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { - super(); - this.connMgr = connMgr; - } - - // API - - @Override - public final void run() { - try { - while (!shutdown) { - synchronized (this) { - wait(1000); - connMgr.closeExpiredConnections(); - connMgr.closeIdleConnections(30, TimeUnit.SECONDS); - } - } - } catch (final InterruptedException ex) { - shutdown(); - } - } - - private void shutdown() { - shutdown = true; - synchronized (this) { - notifyAll(); - } - } - -} diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java index 16bb49123a..9e4b770828 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -6,7 +6,6 @@ import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java similarity index 82% rename from apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java rename to apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java index f72aa0c878..c15d8953f2 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/client/HttpClientSandboxLiveTest.java @@ -1,7 +1,7 @@ -package com.baeldung.httpclient.base; +package com.baeldung.client; + +import java.io.IOException; -import com.baeldung.httpclient.GetRequestMockServer; -import com.baeldung.httpclient.ResponseUtil; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; @@ -12,15 +12,16 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.jupiter.api.Test; -import java.io.IOException; +import com.baeldung.GetRequestMockServer; +import com.baeldung.httpclient.ResponseUtil; /* * NOTE : Need module spring-security-rest-basic-auth to be running */ -public class HttpClientSandboxLiveTest extends GetRequestMockServer { +class HttpClientSandboxLiveTest extends GetRequestMockServer { @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { + final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final AuthScope authscp = new AuthScope("localhost", 8080); credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); diff --git a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java index 3c0f5b7c63..98c6a0b4a7 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java @@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate; * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build * */ -public class RestClientV4LiveManualTest { +class RestClientV4LiveManualTest { final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; @@ -81,7 +81,7 @@ public class RestClientV4LiveManualTest { } @Test - public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { + void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); String urlOverHttps = "https://localhost:8082/httpclient-simple"; HttpGet getMethod = new HttpGet(urlOverHttps); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java index ce8a869e97..0b0d7104d7 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ClientUtil.java @@ -2,8 +2,6 @@ package com.baeldung.httpclient; import java.io.IOException; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.impl.client.CloseableHttpClient; public final class ClientUtil { diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java index 80b16d7f07..90b64092e0 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpAsyncClientV4LiveTest.java @@ -1,4 +1,5 @@ package com.baeldung.httpclient; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java index 446c47c200..6a8a66e87b 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java @@ -9,11 +9,11 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class HttpClientCancelRequestV4LiveTest { +class HttpClientCancelRequestV4LiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -21,18 +21,18 @@ public class HttpClientCancelRequestV4LiveTest { private CloseableHttpResponse response; - @Before + @BeforeEach public final void before() { instance = HttpClientBuilder.create().build(); } - @After + @AfterEach public final void after() throws IllegalStateException, IOException { ResponseUtil.closeResponse(response); } @Test - public final void whenRequestIsCanceled_thenCorrect() throws IOException { + final void whenRequestIsCanceled_thenCorrect() throws IOException { instance = HttpClients.custom().build(); final HttpGet request = new HttpGet(SAMPLE_URL); response = instance.execute(request); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java index 8b83419ba1..ba77a5c7dd 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCookBookV4LiveTest.java @@ -1,5 +1,9 @@ package com.baeldung.httpclient; +import org.apache.http.auth.AuthenticationException; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.auth.BasicScheme; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -181,4 +185,20 @@ class HttpClientCookBookV4LiveTest { } } + @Test + final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { + final HttpPost request = new HttpPost(SAMPLE_POST_URL); + request.setEntity(new StringEntity("in the body of the POST")); + client.execute(request); + } + + @Test + final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { + final HttpPost request = new HttpPost(SAMPLE_POST_URL); + request.setEntity(new StringEntity("in the body of the POST")); + final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); + request.addHeader(new BasicScheme().authenticate(creds, request, null)); + client.execute(request); + } + } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java index f6d65a8d8f..a3f9f3eb47 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientRedirectV4LiveTest.java @@ -1,12 +1,12 @@ package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - import java.io.IOException; import org.apache.http.client.methods.CloseableHttpResponse; diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java index ed22913ddd..5b3ced8b98 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java @@ -92,6 +92,26 @@ class HttpClientTimeoutV4LiveTest extends GetRequestMockServer { } + @Test + final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() { + final RequestConfig requestConfig = RequestConfig.custom() + .setConnectionRequestTimeout(5) + .setConnectTimeout(5) + .setSocketTimeout(2) + .build(); + + final CloseableHttpClient client = HttpClientBuilder.create() + .setDefaultRequestConfig(requestConfig) + .build(); + + final HttpGet request = new HttpGet("http://www.github.com"); + + assertThrows(ConnectTimeoutException.class, () -> { + response = client.execute(request); + }); + } + + @Test void whenSecuredRestApiIsConsumed_then200OK() throws IOException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index 2235d0e9d0..5ced756644 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.httpclient.advancedconfig; +import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; @@ -19,8 +19,10 @@ import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.junit.Rule; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -32,18 +34,29 @@ import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class HttpClientAdvancedConfigurationIntegrationTest { +class HttpClientAdvancedConfigurationIntegrationTest { - @Rule - public WireMockRule serviceMock = new WireMockRule(8089); + public WireMockServer serviceMock; + public WireMockServer proxyMock; - @Rule - public WireMockRule proxyMock = new WireMockRule(8090); + @BeforeEach + public void before () { + serviceMock = new WireMockServer(8089); + serviceMock.start(); + proxyMock = new WireMockServer(8090); + proxyMock.start(); + } + + @AfterEach + public void after () { + serviceMock.stop(); + proxyMock.stop(); + } @Test - public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { + void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException { //given String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) @@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpGet); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(200, response.getStatusLine().getStatusCode()); } @Test - public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { + void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException { //given String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) @@ -82,12 +95,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpClient.execute(httpPost); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); - + assertEquals(200, response.getStatusLine().getStatusCode()); } @Test - public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { + void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { //given proxyMock.stubFor(get(urlMatching(".*")) .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); @@ -107,13 +119,13 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpclient.execute(httpGet); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(200, response.getStatusLine().getStatusCode()); proxyMock.verify(getRequestedFor(urlEqualTo("/private"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } @Test - public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { + void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given proxyMock.stubFor(get(urlMatching("/private")) .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); @@ -152,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpResponse response = httpclient.execute(httpGet, context); //then - assertEquals(response.getStatusLine().getStatusCode(), 200); + assertEquals(200, response.getStatusLine().getStatusCode()); proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic"))); serviceMock.verify(getRequestedFor(urlEqualTo("/private"))); } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java index 5a8c87f4aa..c1b04c6728 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java @@ -12,34 +12,35 @@ import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -public class HttpClientExpandUrlLiveTest { + +class HttpClientExpandUrlLiveTest { private CloseableHttpClient client; - @Before - public final void before() { + @BeforeEach + public final void beforeEach() { client = HttpClientBuilder.create().disableRedirectHandling().build(); } @Test - public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException { + final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException { final String expectedResult = "https://www.baeldung.com/rest-versioning"; final String actualResult = expandSingleLevel("http://bit.ly/3LScTri"); assertThat(actualResult, equalTo(expectedResult)); } @Test - public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException { + final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException { final String expectedResult = "https://www.baeldung.com/rest-versioning"; final String actualResult = expand("http://t.co/e4rDDbnzmk"); assertThat(actualResult, equalTo(expectedResult)); diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java index 9a7a734b65..a7948bcf64 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java @@ -17,7 +17,6 @@ import com.baeldung.GetRequestMockServer; class ApacheHttpClientUnitTest extends GetRequestMockServer { - @Test void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java index c894d72af0..c207aadd28 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -1,7 +1,9 @@ package com.baeldung.httpclient.httpclient.conn; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.util.concurrent.ExecutionException; @@ -24,6 +26,7 @@ import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.ConnectionRequest; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; @@ -33,14 +36,14 @@ import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.util.EntityUtils; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -public class HttpClientConnectionManagementLiveTest { +class HttpClientConnectionManagementLiveTest { // Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection) @Test - public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException { + final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException { try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) { HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80)); final ConnectionRequest connRequest = connManager.requestConnection(route, null); @@ -50,20 +53,20 @@ public class HttpClientConnectionManagementLiveTest { // Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient @Test - public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException { + final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException { PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(poolingConnManager) .build(); client.execute(new HttpGet("https://www.baeldung.com")); - assertTrue(poolingConnManager.getTotalStats() - .getLeased() == 1); + assertEquals(1, poolingConnManager.getTotalStats() + .getLeased()); } // Example 3.2. Using Two HttpClients to Connect to One Target Host Each @Test - public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException { + final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException { HttpGet get1 = new HttpGet("https://www.baeldung.com"); HttpGet get2 = new HttpGet("https://www.google.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); @@ -81,13 +84,13 @@ public class HttpClientConnectionManagementLiveTest { thread1.join(); thread2.join(); - assertTrue(connManager.getTotalStats() - .getLeased() == 0); + assertEquals(0, connManager.getTotalStats() + .getLeased()); } // Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits @Test - public final void whenIncreasingConnectionPool_thenNoEceptions() { + final void whenIncreasingConnectionPool_thenNoEceptions() { try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) { connManager.setMaxTotal(5); connManager.setDefaultMaxPerRoute(4); @@ -98,7 +101,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 4.2. Using Threads to Execute Connections @Test - public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException { + final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException { HttpGet get = new HttpGet("http://www.baeldung.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() @@ -117,7 +120,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 5.1. A Custom Keep Alive Strategy @Test - public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() { + final void whenCustomizingKeepAliveStrategy_thenNoExceptions() { final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) { @@ -148,7 +151,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 6.1. BasicHttpClientConnectionManager Connection Reuse @Test - public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { + final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager(); HttpClientContext context = HttpClientContext.create(); @@ -175,7 +178,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads @Test - public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { + final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { HttpGet get = new HttpGet("http://echo.200please.com"); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(5); @@ -197,20 +200,20 @@ public class HttpClientConnectionManagementLiveTest { // Example 7.1. Setting Socket Timeout to 5 Seconds @Test - public final void whenConfiguringTimeOut_thenNoExceptions() { + final void whenConfiguringTimeOut_thenNoExceptions() { HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80)); try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) { connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom() .setSoTimeout(5000) .build()); - assertTrue(connManager.getSocketConfig(route.getTargetHost()) - .getSoTimeout() == 5000); + assertEquals(5000, connManager.getSocketConfig(route.getTargetHost()) + .getSoTimeout()); } } // Example 8.1. Setting the HttpClient to Check for Stale Connections @Test - public final void whenHttpClientChecksStaleConns_thenNoExceptions() { + final void whenHttpClientChecksStaleConns_thenNoExceptions() { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() @@ -222,7 +225,7 @@ public class HttpClientConnectionManagementLiveTest { // Example 8.2. Using a Stale Connection Monitor Thread @Test - public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException { + final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); HttpClients.custom() .setConnectionManager(connManager) @@ -233,8 +236,8 @@ public class HttpClientConnectionManagementLiveTest { } // Example 9.1. Closing Connection and Releasing Resources - @Test(expected = IllegalStateException.class) - public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException { + @Test + final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(connManager) @@ -248,14 +251,14 @@ public class HttpClientConnectionManagementLiveTest { connManager.close(); connManager.shutdown(); - client.execute(get); - - assertTrue(response.getEntity() == null); + assertThrows(IllegalStateException.class, () -> { + client.execute(get); + }); } @Test // Example 3.2. TESTER VERSION - public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { HttpGet get1 = new HttpGet("https://www.baeldung.com"); HttpGet get2 = new HttpGet("https://www.google.com"); @@ -273,13 +276,13 @@ public class HttpClientConnectionManagementLiveTest { thread2.start(); thread1.join(); thread2.join(1000); - assertTrue(poolingConnManager.getTotalStats() - .getLeased() == 2); + assertEquals(2, poolingConnManager.getTotalStats() + .getLeased()); } @Test // Example 4.2 Tester Version - public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException { + final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException { PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(poolingConnManager) @@ -297,7 +300,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // 6.2 TESTER VERSION - public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { + final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setMaxTotal(5); @@ -316,15 +319,15 @@ public class HttpClientConnectionManagementLiveTest { thread.join(10000); countConnMade++; if (countConnMade == 0) { - assertTrue(thread.getLeasedConn() == 5); + assertEquals(5, thread.getLeasedConn()); } } } @Test - @Ignore("Very Long Running") + @Disabled("Very Long Running") // 8.2 TESTER VERSION - public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException { + final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException { PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(); CloseableHttpClient client = HttpClients.custom() .setConnectionManager(poolingConnManager) @@ -340,10 +343,10 @@ public class HttpClientConnectionManagementLiveTest { thread2.start(); thread2.join(); thread3.start(); - assertTrue(poolingConnManager.getTotalStats() - .getAvailable() == 1); + assertEquals(1, poolingConnManager.getTotalStats() + .getAvailable()); thread3.join(32000); - assertTrue(poolingConnManager.getTotalStats() - .getAvailable() == 0); + assertEquals(0, poolingConnManager.getTotalStats() + .getAvailable()); } } diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java index 4183094621..b09a06050b 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/MultiHttpClientConnThread.java @@ -3,7 +3,6 @@ package com.baeldung.httpclient.httpclient.conn; import java.io.IOException; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 5e2710342d..cd4979541e 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -2,7 +2,6 @@ package com.baeldung.httpclient.httpclient.conn; import java.io.IOException; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java index 4d88211d0d..a47a5cc743 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java @@ -6,18 +6,19 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -public class ApacheHttpClientUnitTest { +class ApacheHttpClientUnitTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final String DUMMY_URL = "https://postman-echo.com/get"; @Test - public void whenUseApacheHttpClient_thenCorrect() throws IOException { + void whenUseApacheHttpClient_thenCorrect() throws IOException { HttpGet request = new HttpGet(DUMMY_URL); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) { diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java index 3a8ff252c2..f04ebff3f8 100644 --- a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java +++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ApacheHttpClientRetryLiveTest { +class ApacheHttpClientRetryLiveTest { private Integer requestCounter; private CloseableHttpClient httpClient; @@ -93,14 +93,14 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() { + void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() { createFailingHttpClient(); assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200"))); assertThat(requestCounter).isEqualTo(4); } @Test - public void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() { + void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() { createDefaultApacheHttpClient(); HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1")); @@ -109,7 +109,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException { + void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException { createDefaultApacheHttpClient(); HttpGet request = new HttpGet(URI.create("https://httpstat.us/500")); @@ -120,7 +120,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() { + void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() { createFailingHttpClient(); HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500")); @@ -129,7 +129,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() { + void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() { createFailingHttpClient(); HttpPut request = new HttpPut(URI.create("https://httpstat.us/500")); @@ -138,7 +138,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() { + void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() { createHttpClientWithRetryHandler(); HttpPost request = new HttpPost(URI.create("https://httpstat.us/200")); @@ -148,7 +148,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() { + void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() { createHttpClientWithCustomRetryHandler(); HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200")); @@ -158,7 +158,7 @@ public class ApacheHttpClientRetryLiveTest { } @Test - public void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() { + void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() { createHttpClientWithRetriesDisabled(); HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));