diff --git a/cdi/pom.xml b/cdi/pom.xml index fec12a9b16..226ca529e1 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -1,8 +1,8 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cdi 1.0-SNAPSHOT @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-4 + ../parent-spring-5 @@ -26,28 +26,22 @@ weld-se-core ${weld-se-core.version} - - org.hamcrest - hamcrest - ${hamcrest.version} - test - org.assertj assertj-core ${assertj-core.version} test - - org.springframework - spring-context - ${spring.version} - org.aspectj aspectjweaver ${aspectjweaver.version} + + org.springframework + spring-context + ${spring.version} + org.springframework spring-test @@ -61,7 +55,6 @@ 3.0.5.Final 1.9.2 3.10.0 - 5.1.2.RELEASE diff --git a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java index f529e219a6..0b70516146 100644 --- a/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java +++ b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java @@ -10,5 +10,6 @@ public class CopyListServiceUnitTest { @Test(expected = UnsupportedOperationException.class) public void whenModifyCopyOfList_thenThrowsException() { List copyList = List.copyOf(Arrays.asList(1, 2, 3, 4)); + copyList.add(4); } } diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml index 32c522dab5..b909572afe 100644 --- a/core-java-modules/core-java-exceptions-3/pom.xml +++ b/core-java-modules/core-java-exceptions-3/pom.xml @@ -30,5 +30,4 @@ 3.10.0 - - \ No newline at end of file + diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java new file mode 100644 index 0000000000..c2c76bdc46 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/nullmethodparameter/NullParameterExample.java @@ -0,0 +1,17 @@ +package com.baeldung.nullmethodparameter; + +public class NullParameterExample { + public void processSomethingNotNull(Object myParameter) { + if (myParameter == null) { + throw new IllegalArgumentException("Parameter 'myParameter' cannot be null"); + } + //Do something with the parameter + } + + public void processSomethingElseNotNull(Object myParameter) { + if (myParameter == null) { + throw new NullPointerException("Parameter 'myParameter' cannot be null"); + } + //Do something with the parameter + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java new file mode 100644 index 0000000000..aa4b332e52 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/nullmethodparameter/NullParameterExampleUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.nullmethodparameter; + +import org.junit.Test; + +public class NullParameterExampleUnitTest { + @Test(expected = IllegalArgumentException.class) + public void givenNullParameter_whenProcessSomethingNotNull_thenIllegalArgumentException() { + NullParameterExample example = new NullParameterExample(); + example.processSomethingNotNull(null); + } + + @Test(expected = NullPointerException.class) + public void givenNullParameter_whenProcessSomethingElseNotNull_thenNullPointerException() { + NullParameterExample example = new NullParameterExample(); + example.processSomethingElseNotNull(null); + } +} diff --git a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java new file mode 100644 index 0000000000..ca6b25b3e7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2.java @@ -0,0 +1,60 @@ +package com.baeldung.algorithms.largestpowerof2; + +import org.nd4j.linalg.io.Assert; + +public class LargestPowerOf2 { + public long findLargestPowerOf2LessThanTheGivenNumber(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long firstPowerOf2 = 1; + long nextPowerOf2 = 2; + + while (nextPowerOf2 < input) { + firstPowerOf2 = nextPowerOf2; + nextPowerOf2 = nextPowerOf2 * 2; + } + return firstPowerOf2; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) { + Assert.isTrue(input > 1, "Invalid input"); + + long temp = input; + if (input % 2 == 0) { + temp = input - 1; + } + + // Find log base 2 of a given number + long power = (long) (Math.log(temp) / Math.log(2)); + long result = (long) Math.pow(2, power); + + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + for (long i = input - 1; i > 1; i--) { + if ((i & (i - 1)) == 0) { + result = i; + break; + } + } + return result; + } + + public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) { + Assert.isTrue(input > 1, "Invalid input"); + long result = 1; + long powerOf2; + + for (long i = 0; i < Long.BYTES * 8; i++) { + powerOf2 = 1 << i; + if (powerOf2 >= input) { + break; + } + result = powerOf2; + } + return result; + } +} diff --git a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java new file mode 100644 index 0000000000..63f7b03cf7 --- /dev/null +++ b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/largestpowerof2/LargestPowerOf2UnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.algorithms.largestpowerof2; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class LargestPowerOf2UnitTest { + private long input; + private long expectedResult; + + public LargestPowerOf2UnitTest(long input, long expectedResult) { + this.input = input; + this.expectedResult = expectedResult; + } + + @Parameterized.Parameters(name = "{index}: verifyLargestPowerOf2LessThanTheGivenNumber({0}) = {1}") + public static Collection data() { + return Arrays.asList(new Object[][] { { 2, 1 }, { 4, 2 }, { 500, 256 }, { 512, 256 }, { 1050, 1024 } }); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumber() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberUsingLogBase2() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitwiseAnd() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test + public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitShiftApproach() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + + long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(input); + + Assert.assertEquals(expectedResult, result); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInvalidInput_ShouldThrowException() { + LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2(); + largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(1); + } +} \ No newline at end of file diff --git a/docker/docker-spring-boot/README.md b/docker/docker-spring-boot/README.md deleted file mode 100644 index 78f13a3652..0000000000 --- a/docker/docker-spring-boot/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Article: - -- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images) diff --git a/gradle-5/settings.gradle b/gradle-5/settings.gradle index 1997e12ca5..5384d071e7 100644 --- a/gradle-5/settings.gradle +++ b/gradle-5/settings.gradle @@ -1,3 +1,4 @@ rootProject.name='gradle-5-articles' include 'java-exec' -include 'unused-dependencies' \ No newline at end of file +include 'unused-dependencies' +include 'source-sets' \ No newline at end of file diff --git a/gradle-5/source-sets/.gitignore b/gradle-5/source-sets/.gitignore new file mode 100644 index 0000000000..84c048a73c --- /dev/null +++ b/gradle-5/source-sets/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/gradle-5/source-sets/build.gradle b/gradle-5/source-sets/build.gradle new file mode 100644 index 0000000000..8325450cfd --- /dev/null +++ b/gradle-5/source-sets/build.gradle @@ -0,0 +1,67 @@ + +apply plugin: "eclipse" +apply plugin: "java" + +description = "Source Sets example" + +task printSourceSetInformation(){ + description = "Print source set information" + + doLast{ + sourceSets.each { srcSet -> + println "["+srcSet.name+"]" + print "-->Source directories: "+srcSet.allJava.srcDirs+"\n" + print "-->Output directories: "+srcSet.output.classesDirs.files+"\n" + print "-->Compile classpath:\n" + srcSet.compileClasspath.files.each { + print " "+it.path+"\n" + } + println "" + } + } +} + +sourceSets{ + itest { + compileClasspath += sourceSets.main.output + runtimeClasspath += sourceSets.main.output + java { + } + } +} + +test { + testLogging { + events "passed","skipped", "failed" + } +} + +dependencies { + implementation('org.apache.httpcomponents:httpclient:4.5.12') + testImplementation('junit:junit:4.12') + itestImplementation('com.google.guava:guava:29.0-jre') +} + +task itest(type: Test) { + description = "Run integration tests" + group = "verification" + testClassesDirs = sourceSets.itest.output.classesDirs + classpath = sourceSets.itest.runtimeClasspath +} + +itest { + testLogging { + events "passed","skipped", "failed" + } +} + +configurations { + itestImplementation.extendsFrom(testImplementation) + itestRuntimeOnly.extendsFrom(testRuntimeOnly) +} + +eclipse { + classpath { + plusConfigurations+=[configurations.itestCompileClasspath] + } +} \ No newline at end of file diff --git a/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java new file mode 100644 index 0000000000..3312c5b6e5 --- /dev/null +++ b/gradle-5/source-sets/src/itest/java/com/baeldung/itest/SourceSetsItest.java @@ -0,0 +1,25 @@ +package com.baeldung.itest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +import com.baeldung.main.SourceSetsObject; +import com.google.common.collect.ImmutableList; + +public class SourceSetsItest { + + @Test + public void givenImmutableList_whenRun_ThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + List someStrings = ImmutableList.of("Baeldung", "is", "cool"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); + assertThat(someStrings.size(), is(3)); + } +} diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java new file mode 100644 index 0000000000..319894d336 --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsMain.java @@ -0,0 +1,9 @@ +package com.baeldung.main; + +public class SourceSetsMain { + + public static void main(String[] args) { + System.out.println("Hell..oh...world!"); + } + +} diff --git a/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java new file mode 100644 index 0000000000..130121789c --- /dev/null +++ b/gradle-5/source-sets/src/main/java/com/baeldung/main/SourceSetsObject.java @@ -0,0 +1,21 @@ +package com.baeldung.main; + +public class SourceSetsObject { + + private final String user; + private final String password; + + public SourceSetsObject(String user, String password) { + this.user = user; + this.password = password; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + +} diff --git a/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java new file mode 100644 index 0000000000..b033eb8e52 --- /dev/null +++ b/gradle-5/source-sets/src/test/java/com/baeldung/test/SourceSetsTest.java @@ -0,0 +1,20 @@ +package com.baeldung.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; + +import com.baeldung.main.SourceSetsObject; + +public class SourceSetsTest { + + @Test + public void whenRun_ThenSuccess() { + + SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum"); + + assertThat(underTest.getUser(), is("lorem")); + assertThat(underTest.getPassword(), is("ipsum")); + } +} diff --git a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java index 5d90d0f288..171f2f17db 100644 --- a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java +++ b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java @@ -24,7 +24,6 @@ public class SmurfsRepository { smurfs.put("Architect", new Smurf("Architect", true, true)); smurfs.put("Baby", new Smurf("Baby", true, true)); smurfs.put("Baker", new Smurf("Baker", true, true)); - smurfs.put("Baker", new Smurf("Baker", true, true)); } public List findAll() { diff --git a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java index 255a024cdc..938257ba17 100644 --- a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java +++ b/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java @@ -5,8 +5,6 @@ public class Smurf { private boolean comic; private boolean cartoon; - public Smurf() {} - public Smurf(String name, boolean comic, boolean cartoon) { this.name = name; this.comic = comic; diff --git a/logging-modules/log-mdc/Dockerfile b/logging-modules/log-mdc/Dockerfile new file mode 100644 index 0000000000..e69de29bb2 diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index e367a63de6..bc4800ea37 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 diff --git a/open-liberty/pom.xml b/open-liberty/pom.xml index d6588ce49a..0e8b159043 100644 --- a/open-liberty/pom.xml +++ b/open-liberty/pom.xml @@ -27,6 +27,7 @@ org.apache.derby derby ${version.derby} + provided @@ -70,27 +71,16 @@ io.openliberty.tools liberty-maven-plugin ${version.liberty-maven-plugin} - - - org.apache.maven.plugins - maven-dependency-plugin - ${version.maven-dependency-plugin} - - - copy-derby-dependency - package - - copy-dependencies - - - derby - ${project.build.directory}/liberty/wlp/usr/shared/resources/ - - ${testServerHttpPort} - - - - + + + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + org.apache.derby + derby + ${version.derby} + + + org.apache.maven.plugins @@ -112,8 +102,7 @@ 8.0.0 3.2 10.14.2.0 - 3.1 - 2.10 + 3.3-M3 3.2.3 4.12 1.0.5 diff --git a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java index 3fe858936a..8cfee8f5d6 100644 --- a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java +++ b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/jpa/equality/EqualByBusinessKey.java @@ -44,7 +44,7 @@ public class EqualByBusinessKey { return false; } if (obj instanceof EqualByBusinessKey) { - if (((EqualByBusinessKey) obj).getEmail() == getEmail()) { + if (((EqualByBusinessKey) obj).getEmail().equals(getEmail())) { return true; } } diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java index bdfb8e890f..d824505629 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Course.java @@ -1,14 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "course") public class Course { @@ -18,31 +13,55 @@ public class Course { private Long id; @ManyToMany(mappedBy = "likedCourses") - private Set likes; + private Set likes = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "course") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Course() { } + public Course(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + + public Set getLikes() { + return likes; + } + + public void setLikes(Set likes) { + this.likes = likes; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java index 4951f766bc..b89cc1dae9 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRating.java @@ -1,12 +1,6 @@ package com.baeldung.manytomany.model; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.Table; +import javax.persistence.*; @Entity @Table(name = "course_rating") @@ -16,12 +10,12 @@ public class CourseRating { private CourseRatingKey id; @ManyToOne - @MapsId("student_id") + @MapsId("studentId") @JoinColumn(name = "student_id") private Student student; @ManyToOne - @MapsId("course_id") + @MapsId("courseId") @JoinColumn(name = "course_id") private Course course; @@ -31,26 +25,38 @@ public class CourseRating { public CourseRating() { } - public int getRating() { - return rating; - } - - public void setRating(int rating) { - this.rating = rating; - } - public CourseRatingKey getId() { return id; } + public void setId(CourseRatingKey id) { + this.id = id; + } + public Student getStudent() { return student; } + public void setStudent(Student student) { + this.student = student; + } + public Course getCourse() { return course; } + public void setCourse(Course course) { + this.course = course; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java index 4e7430ed92..a4b2df9b07 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRatingKey.java @@ -1,9 +1,8 @@ package com.baeldung.manytomany.model; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.Embeddable; +import java.io.Serializable; @Embeddable public class CourseRatingKey implements Serializable { @@ -17,14 +16,27 @@ public class CourseRatingKey implements Serializable { public CourseRatingKey() { } + public CourseRatingKey(Long studentId, Long courseId) { + this.studentId = studentId; + this.courseId = courseId; + } + public Long getStudentId() { return studentId; } + public void setStudentId(Long studentId) { + this.studentId = studentId; + } + public Long getCourseId() { return courseId; } + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java index e1f30af883..ba914b564d 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/CourseRegistration.java @@ -1,14 +1,8 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; import java.time.LocalDateTime; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - @Entity @Table(name = "course_registration") public class CourseRegistration { @@ -36,6 +30,14 @@ public class CourseRegistration { public CourseRegistration() { } + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + public Student getStudent() { return student; } @@ -68,10 +70,6 @@ public class CourseRegistration { this.grade = grade; } - public Long getId() { - return id; - } - @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java index 00561593a6..53c5d88a57 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomany/model/Student.java @@ -1,16 +1,9 @@ package com.baeldung.manytomany.model; +import javax.persistence.*; +import java.util.HashSet; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - @Entity @Table(name = "student") public class Student { @@ -21,35 +14,55 @@ public class Student { @ManyToMany @JoinTable(name = "course_like", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) - private Set likedCourses; + private Set likedCourses = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set ratings; + private Set ratings = new HashSet<>(); @OneToMany(mappedBy = "student") - private Set registrations; + private Set registrations = new HashSet<>(); // additional properties public Student() { } + public Student(Long id) { + this.id = id; + } + public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + public Set getLikedCourses() { return likedCourses; } + public void setLikedCourses(Set likedCourses) { + this.likedCourses = likedCourses; + } + public Set getRatings() { return ratings; } + public void setRatings(Set ratings) { + this.ratings = ratings; + } + public Set getRegistrations() { return registrations; } + public void setRegistrations(Set registrations) { + this.registrations = registrations; + } + @Override public int hashCode() { final int prime = 31; diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java index 5e4334f5d4..f5b02ec2c1 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyIntegrationTest.java @@ -1,17 +1,27 @@ package com.baeldung.manytomany; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - +import com.baeldung.manytomany.model.Course; +import com.baeldung.manytomany.model.CourseRating; +import com.baeldung.manytomany.model.CourseRatingKey; +import com.baeldung.manytomany.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) @ContextConfiguration(classes = ManyToManyTestConfiguration.class) @DirtiesContext +@Transactional public class ManyToManyIntegrationTest { @PersistenceContext @@ -21,4 +31,25 @@ public class ManyToManyIntegrationTest { public void contextStarted() { } + @Test + public void whenCourseRatingPersisted_thenCorrect() { + Student student = new Student(101L); + entityManager.persist(student); + + Course course = new Course(201L); + entityManager.persist(course); + + CourseRating courseRating = new CourseRating(); + courseRating.setId(new CourseRatingKey()); + courseRating.setStudent(student); + courseRating.setCourse(course); + courseRating.setRating(100); + entityManager.persist(courseRating); + + CourseRating persistedCourseRating = entityManager.find(CourseRating.class, new CourseRatingKey(101L, 201L)); + + assertThat(persistedCourseRating, notNullValue()); + assertThat(persistedCourseRating.getStudent().getId(), is(101L)); + assertThat(persistedCourseRating.getCourse().getId(), is(201L)); + } } diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java index 1cc3621f0d..fa12828074 100644 --- a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java +++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomany/ManyToManyTestConfiguration.java @@ -1,20 +1,21 @@ package com.baeldung.manytomany; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + @Configuration @PropertySource("manytomany/test.properties") public class ManyToManyTestConfiguration { @@ -23,8 +24,8 @@ public class ManyToManyTestConfiguration { public DataSource dataSource() { EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); return dbBuilder.setType(EmbeddedDatabaseType.H2) - .addScript("classpath:/manytomany/db.sql") - .build(); + .addScript("classpath:/manytomany/db.sql") + .build(); } @Bean @@ -44,6 +45,13 @@ public class ManyToManyTestConfiguration { return result; } + @Bean + JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + public JpaVendorAdapter jpaVendorAdapter() { return new HibernateJpaVendorAdapter(); } diff --git a/pom.xml b/pom.xml index 3565c2dc4b..ffdfe4cffa 100644 --- a/pom.xml +++ b/pom.xml @@ -701,6 +701,7 @@ spring-rest-compress spring-rest-hal-browser spring-rest-http + spring-rest-http-2 spring-rest-query-language spring-rest-shell spring-rest-simple diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 09eb90d110..67356abdef 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -30,9 +30,48 @@ io.quarkus quarkus-resteasy + + io.quarkus + quarkus-resteasy-jackson + ${quarkus.version} + + + io.quarkus + quarkus-hibernate-orm-panache + ${quarkus.version} + + + io.quarkus + quarkus-jdbc-h2 + ${quarkus.version} + + + org.apache.commons + commons-lang3 + 3.9 + + + org.projectlombok + lombok + 1.18.6 + provided + io.quarkus quarkus-junit5 + ${quarkus.version} + test + + + io.quarkus + quarkus-junit5-mockito + ${quarkus.version} + test + + + io.quarkus + quarkus-test-h2 + ${quarkus.version} test @@ -117,7 +156,8 @@ 2.22.0 - 0.15.0 + 1.7.0.Final + 5.6.0 diff --git a/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java new file mode 100644 index 0000000000..88c3f0ed6e --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/LibraryResource.java @@ -0,0 +1,25 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.service.LibraryService; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Set; + +@Path("/library") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class LibraryResource { + + @Inject + LibraryService libraryService; + + @GET + @Path("/book") + public Set findBooks(@QueryParam("query") String query) { + return libraryService.find(query); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java new file mode 100644 index 0000000000..7d258c1934 --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/model/Book.java @@ -0,0 +1,17 @@ +package com.baeldung.quarkus.model; + +import io.quarkus.hibernate.orm.panache.PanacheEntity; +import lombok.*; + +import javax.persistence.Entity; + +@Data +@Entity +@AllArgsConstructor +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Book extends PanacheEntity { + private String title; + private String author; +} + diff --git a/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java new file mode 100644 index 0000000000..b142fa569b --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/repository/BookRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.model.Book; +import io.quarkus.hibernate.orm.panache.PanacheRepository; + +import javax.enterprise.context.ApplicationScoped; +import java.util.stream.Stream; + +import static io.quarkus.panache.common.Parameters.with; + +@ApplicationScoped +public class BookRepository implements PanacheRepository { + + public Stream findBy(String query) { + return find("author like :query or title like :query", with("query", "%"+query+"%")).stream(); + } + +} diff --git a/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java new file mode 100644 index 0000000000..be687589bf --- /dev/null +++ b/quarkus/src/main/java/com/baeldung/quarkus/service/LibraryService.java @@ -0,0 +1,28 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; +import java.util.Set; + +import static java.util.stream.Collectors.toSet; + +@Transactional +@ApplicationScoped +public class LibraryService { + + @Inject + BookRepository bookRepository; + + public Set find(String query) { + if (query == null) { + return bookRepository.findAll().stream().collect(toSet()); + } + + return bookRepository.findBy(query).collect(toSet()); + } + +} diff --git a/quarkus/src/main/resources/application.properties b/quarkus/src/main/resources/application.properties index 3f05d2198f..283cf763b9 100644 --- a/quarkus/src/main/resources/application.properties +++ b/quarkus/src/main/resources/application.properties @@ -1,3 +1,12 @@ # Configuration file # key = value -greeting=Good morning \ No newline at end of file +greeting=Good morning + +quarkus.datasource.db-kind = h2 +quarkus.datasource.jdbc.url = jdbc:h2:tcp://localhost/mem:test + +quarkus.hibernate-orm.database.generation = drop-and-create + +%custom-profile.quarkus.datasource.jdbc.url = jdbc:h2:file:./testdb + +quarkus.http.test-port=0 diff --git a/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java new file mode 100644 index 0000000000..b9175ae457 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/CustomLibraryResourceManualTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.utils.CustomTestProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItems; + +@QuarkusTest +@TestProfile(CustomTestProfile.class) +class CustomLibraryResourceManualTest { + + public static final String BOOKSTORE_ENDPOINT = "/custom/library/book"; + + @Test + void whenGetBooksGivenNoQuery_thenAllBooksShouldBeReturned() { + given().contentType(ContentType.JSON) + .when().get(BOOKSTORE_ENDPOINT) + .then().statusCode(200) + .body("size()", is(2)) + .body("title", hasItems("Foundation", "Dune")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java new file mode 100644 index 0000000000..f3a30a2383 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryHttpEndpointIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; + +@QuarkusTest +@TestHTTPEndpoint(LibraryResource.class) +class LibraryHttpEndpointIntegrationTest { + + @Test + void whenGetBooks_thenShouldReturnSuccessfully() { + given().contentType(ContentType.JSON) + .when().get("book") + .then().statusCode(200); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java new file mode 100644 index 0000000000..1931460aaa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceHttpResourceIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.http.TestHTTPEndpoint; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.URL; + +import static io.restassured.RestAssured.given; +import static java.nio.charset.Charset.defaultCharset; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class LibraryResourceHttpResourceIntegrationTest { + + @TestHTTPEndpoint(LibraryResource.class) + @TestHTTPResource("book") + URL libraryEndpoint; + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get(libraryEndpoint) + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + + @Test + void whenGetBooks_thenBooksShouldBeFound() throws IOException { + assertTrue(IOUtils.toString(libraryEndpoint.openStream(), defaultCharset()).contains("Asimov")); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java new file mode 100644 index 0000000000..48ec1786fa --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceInjectSpyIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import com.baeldung.quarkus.service.LibraryService; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.verify; + +@QuarkusTest +class LibraryResourceInjectSpyIntegrationTest { + + @InjectSpy + LibraryService libraryService; + + @Test + void whenGetBooksByAuthor_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Asimov") + .when().get("/library/book") + .then().statusCode(200); + + verify(libraryService).find("Asimov"); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java new file mode 100644 index 0000000000..28eba8da44 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/LibraryResourceIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasItem; + +@QuarkusTest +class LibraryResourceIntegrationTest { + + @Test + void whenGetBooksByTitle_thenBookShouldBeFound() { + given().contentType(ContentType.JSON).param("query", "Dune") + .when().get("/library/book") + .then().statusCode(200) + .body("size()", is(1)) + .body("title", hasItem("Dune")) + .body("author", hasItem("Frank Herbert")); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java index 9ada64b6a5..e6c8a3b8fb 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java @@ -1,8 +1,11 @@ package com.baeldung.quarkus; -import io.quarkus.test.junit.SubstrateTest; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; -@SubstrateTest +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) public class NativeHelloResourceIT extends HelloResourceUnitTest { // Execute the same tests but in native mode. diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java new file mode 100644 index 0000000000..0c11fa6fb4 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeLibraryResourceIT.java @@ -0,0 +1,10 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.NativeImageTest; + +@NativeImageTest +@QuarkusTestResource(H2DatabaseTestResource.class) +class NativeLibraryResourceIT extends LibraryHttpEndpointIntegrationTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..7d811b2268 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.quarkus.repository; + +import com.baeldung.quarkus.utils.QuarkusTransactionalTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTransactionalTest +class BookRepositoryIntegrationTest { + + @Inject + BookRepository bookRepository; + + @Test + void givenBookInRepository_whenFindByAuthor_thenShouldReturnBookFromRepository() { + assertTrue(bookRepository.findBy("Herbert").findAny().isPresent()); + } +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java new file mode 100644 index 0000000000..f0b7260c7d --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceInjectMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectMock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +@QuarkusTest +class LibraryServiceInjectMockUnitTest { + + @Inject + LibraryService libraryService; + + @InjectMock + BookRepository bookRepository; + + @BeforeEach + void setUp() { + when(bookRepository.findBy("Frank Herbert")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Dune", "Frank Herbert"), + new Book("Children of Dune", "Frank Herbert")})); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Frank Herbert").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java new file mode 100644 index 0000000000..16cce4d726 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.quarkus.service; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import javax.inject.Inject; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +@QuarkusTest +class LibraryServiceIntegrationTest { + + @Inject + LibraryService libraryService; + + @Test + void whenFindByAuthor_thenBookShouldBeFound() { + assertFalse(libraryService.find("Frank Herbert").isEmpty()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java new file mode 100644 index 0000000000..e2d40a0a0b --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/service/LibraryServiceQuarkusMockUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.quarkus.service; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; +import com.baeldung.quarkus.utils.TestBookRepository; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import javax.inject.Inject; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class LibraryServiceQuarkusMockUnitTest { + + @Inject + LibraryService libraryService; + + @BeforeEach + void setUp() { + BookRepository mock = Mockito.mock(TestBookRepository.class); + Mockito.when(mock.findBy("Asimov")) + .thenReturn(Arrays.stream(new Book[] { + new Book("Foundation", "Isaac Asimov"), + new Book("I Robot", "Isaac Asimov")})); + QuarkusMock.installMockForType(mock, BookRepository.class); + } + + @Test + void whenFindByAuthor_thenBooksShouldBeFound() { + assertEquals(2, libraryService.find("Asimov").size()); + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java new file mode 100644 index 0000000000..75fb736acc --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java @@ -0,0 +1,26 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +public class CustomTestProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Collections.singletonMap("quarkus.resteasy.path", "/custom"); + } + + @Override + public Set> getEnabledAlternatives() { + return Collections.singleton(TestBookRepository.class); + } + + @Override + public String getConfigProfile() { + return "custom-profile"; + } + +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java new file mode 100644 index 0000000000..d02cff2662 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/QuarkusTransactionalTest.java @@ -0,0 +1,18 @@ +package com.baeldung.quarkus.utils; + +import io.quarkus.test.junit.QuarkusTest; + +import javax.enterprise.inject.Stereotype; +import javax.transaction.Transactional; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@QuarkusTest +@Stereotype +@Transactional +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface QuarkusTransactionalTest { +} diff --git a/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java new file mode 100644 index 0000000000..baaa9fd005 --- /dev/null +++ b/quarkus/src/test/java/com/baeldung/quarkus/utils/TestBookRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.quarkus.utils; + +import com.baeldung.quarkus.model.Book; +import com.baeldung.quarkus.repository.BookRepository; + +import javax.annotation.PostConstruct; +import javax.annotation.Priority; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +@Priority(1) +@Alternative +@ApplicationScoped +public class TestBookRepository extends BookRepository { + + @PostConstruct + public void init() { + persist(new Book("Dune", "Frank Herbert"), + new Book("Foundation", "Isaac Asimov")); + } + +} diff --git a/spring-5-webflux/.gitignore b/spring-5-webflux/.gitignore index aa4871eeea..4dff7c9a4b 100644 --- a/spring-5-webflux/.gitignore +++ b/spring-5-webflux/.gitignore @@ -1,2 +1,2 @@ # Files # -*.log \ No newline at end of file +*.log diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java new file mode 100644 index 0000000000..5ae6784536 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/AsyncVsWebFluxApp.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.asyncvsflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AsyncVsWebFluxApp { + public static void main(String[] args) { + SpringApplication.run(AsyncVsWebFluxApp.class, args); + } +} \ No newline at end of file diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java new file mode 100644 index 0000000000..8ef1ef3e7e --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.asyncvsflux; + +import java.time.Duration; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +@RestController +public class WebFluxController { + + @GetMapping("/flux_result") + public Mono getResult(ServerHttpRequest request) { + return Mono.defer(() -> Mono.just("Result is ready!")) + .delaySubscription(Duration.ofMillis(500)); + } +} diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java new file mode 100644 index 0000000000..3a78047ab8 --- /dev/null +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/asyncvsflux/WebFluxFilter.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.asyncvsflux; + +import java.time.Duration; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Mono; + +@Component +public class WebFluxFilter implements org.springframework.web.server.WebFilter { + + @Override + public Mono filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) { + return Mono + .delay(Duration.ofMillis(200)) + .then( + webFilterChain.filter(serverWebExchange) + ); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java new file mode 100644 index 0000000000..977de5534d --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/NotificationApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.conditionalonproperty; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class NotificationApplication { + + public static void main(String[] args) { + SpringApplication.run(NotificationApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java new file mode 100644 index 0000000000..ffd942cd02 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/config/NotificationConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.conditionalonproperty.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; +import com.baeldung.conditionalonproperty.service.SmsNotification; + +@Configuration +public class NotificationConfig { + + @Bean(name = "emailNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "email") + public NotificationSender notificationSender() { + return new EmailNotification(); + } + + @Bean(name = "smsNotification") + @ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms") + public NotificationSender notificationSender2() { + return new SmsNotification(); + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java new file mode 100644 index 0000000000..c66800f817 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/EmailNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class EmailNotification implements NotificationSender { + + @Override + public String send(String message) { + return "Email Notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java new file mode 100644 index 0000000000..945306e7c4 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/NotificationSender.java @@ -0,0 +1,5 @@ +package com.baeldung.conditionalonproperty.service; + +public interface NotificationSender { + String send(String message); +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java new file mode 100644 index 0000000000..dcf611da19 --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/java/com/baeldung/conditionalonproperty/service/SmsNotification.java @@ -0,0 +1,10 @@ +package com.baeldung.conditionalonproperty.service; + +public class SmsNotification implements NotificationSender { + + @Override + public String send(String message) { + return "SMS notification: " + message; + } + +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties index 4456c78e5d..03f753abf9 100644 --- a/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/main/resources/application.properties @@ -1,2 +1,4 @@ spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto = update + +notification.service=email diff --git a/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java new file mode 100644 index 0000000000..fb9b177e5f --- /dev/null +++ b/spring-boot-modules/spring-boot-autoconfiguration/src/test/java/com/baeldung/conditionalonproperty/NotificationUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.conditionalonproperty; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import com.baeldung.conditionalonproperty.config.NotificationConfig; +import com.baeldung.conditionalonproperty.service.EmailNotification; +import com.baeldung.conditionalonproperty.service.NotificationSender; + +public class NotificationUnitTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenValueSetToEmail_thenCreateEmailNotification() { + this.contextRunner.withPropertyValues("notification.service=email") + .withUserConfiguration(NotificationConfig.class) + .run(context -> { + assertThat(context).hasBean("emailNotification"); + NotificationSender notificationSender = context.getBean(EmailNotification.class); + assertThat(notificationSender.send("Hello From Baeldung!")).isEqualTo("Email Notification: Hello From Baeldung!"); + assertThat(context).doesNotHaveBean("smsNotification"); + }); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java new file mode 100644 index 0000000000..ece06f3fc5 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncController.java @@ -0,0 +1,23 @@ +package com.baeldung.asyncvsflux; + +import java.util.concurrent.CompletableFuture; +import javax.servlet.http.HttpServletRequest; +import org.springframework.scheduling.annotation.Async; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AsyncController { + + @GetMapping("/async_result") + @Async + public CompletableFuture getResultAsyc(HttpServletRequest request) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return CompletableFuture.completedFuture("Result is ready!"); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java new file mode 100644 index 0000000000..5a8ac4d9df --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.asyncvsflux; + +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import org.springframework.stereotype.Component; + +@Component +public class AsyncFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + filterChain.doFilter(servletRequest, servletResponse); + } + + @Override + public void destroy() { + + } +} diff --git a/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java new file mode 100644 index 0000000000..3905199468 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/asyncvsflux/AsyncVsWebFluxApp.java @@ -0,0 +1,13 @@ +package com.baeldung.asyncvsflux; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication +@EnableAsync +public class AsyncVsWebFluxApp { + public static void main(String[] args) { + SpringApplication.run(AsyncVsWebFluxApp.class, args); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 9ae6d8341a..39046ee6d9 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -49,6 +49,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-data-rest + mysql @@ -99,24 +103,7 @@ io.springfox - springfox-swagger2 - ${spring.fox.version} - - - io.springfox - springfox-swagger-ui - ${spring.fox.version} - - - - io.springfox - springfox-data-rest - ${spring.fox.version} - - - - io.springfox - springfox-bean-validators + springfox-boot-starter ${spring.fox.version} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index 434a8d77cb..b404b0c2f8 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -1,13 +1,9 @@ package com.baeldung.swagger2boot.configuration; -import org.springframework.boot.autoconfigure.domain.EntityScan; +import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; - -import com.baeldung.swagger2boot.plugin.EmailAnnotationPlugin; - import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; @@ -16,13 +12,16 @@ import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger.web.*; -import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; @Configuration -@EnableSwagger2WebMvc @Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SpringFoxConfig { @@ -43,8 +42,8 @@ public class SpringFoxConfig { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) .build(); } diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml index bb515fcb36..9e706cc239 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml @@ -41,7 +41,7 @@ 1.11.632 - 1.2.1.RELEASE + 2.0.2.RELEASE 2.2.1.RELEASE diff --git a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java index e4d7fcdc99..0ed06afd00 100644 --- a/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java +++ b/spring-core-2/src/main/java/com/baeldung/springevents/synchronous/CustomSpringEventPublisher.java @@ -10,7 +10,7 @@ public class CustomSpringEventPublisher { @Autowired private ApplicationEventPublisher applicationEventPublisher; - public void publishEvent(final String message) { + public void publishCustomEvent(final String message) { System.out.println("Publishing custom event. "); final CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message); applicationEventPublisher.publishEvent(customSpringEvent); diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index 4f8035bcbe..d41f0114ca 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -17,7 +17,7 @@ public class AsynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() throws InterruptedException { - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing asynchronous custom event. "); } } diff --git a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index 1d624d2289..d4d718f980 100644 --- a/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -22,7 +22,7 @@ public class SynchronousCustomSpringEventsIntegrationTest { @Test public void testCustomSpringEvents() { isTrue(!listener.isHitCustomEventHandler(), "The value should be false"); - publisher.publishEvent("Hello world!!"); + publisher.publishCustomEvent("Hello world!!"); System.out.println("Done publishing synchronous custom event. "); isTrue(listener.isHitCustomEventHandler(), "Now the value should be changed to true"); } diff --git a/spring-rest-http-2/README.md b/spring-rest-http-2/README.md new file mode 100644 index 0000000000..74ec59e0b5 --- /dev/null +++ b/spring-rest-http-2/README.md @@ -0,0 +1,10 @@ +## Spring REST HTTP 2 + +This module contains articles about HTTP in REST APIs with Spring + +### The Course +The "REST With Spring 2" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + + diff --git a/spring-rest-http-2/pom.xml b/spring-rest-http-2/pom.xml new file mode 100644 index 0000000000..8678d7243d --- /dev/null +++ b/spring-rest-http-2/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + spring-rest-http-2 + 0.1-SNAPSHOT + spring-rest-http-2 + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-swagger2 + ${swagger2.version} + + + io.springfox + springfox-swagger-ui + ${swagger2.version} + + + + + 2.9.2 + + + diff --git a/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java b/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java new file mode 100644 index 0000000000..f8127f3686 --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/SpringBootRest2Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootRest2Application { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRest2Application.class, args); + } +} diff --git a/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java new file mode 100644 index 0000000000..8a9a921036 --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/config/SwaggerConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.swaggerui.disable.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Profile("!prod") +// @Profile("swagger") +// @Profile("!prod && swagger") +// @ConditionalOnExpression(value = "${useSwagger:false}") +@Configuration +@EnableSwagger2 +public class SwaggerConfig implements WebMvcConfigurer { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).select() + .apis(RequestHandlerSelectors.basePackage("com.baeldung")) + .paths(PathSelectors.regex("/.*")) + .build(); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } +} diff --git a/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java new file mode 100644 index 0000000000..8f8115197e --- /dev/null +++ b/spring-rest-http-2/src/main/java/com/baeldung/swaggerui/disable/controllers/VersionController.java @@ -0,0 +1,40 @@ +package com.baeldung.swaggerui.disable.controllers; + +import io.swagger.annotations.ApiOperation; +import org.springframework.core.env.Environment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class VersionController { + + private final Environment environment; + + public VersionController(Environment environment) { + this.environment = environment; + } + + @ApiOperation(value = "Get the currently deployed API version and active Spring profiles") + @GetMapping("/api/version") + public Version getVersion() { + return new Version("1.0", environment.getActiveProfiles()); + } + + private static class Version { + private final String version; + private String[] activeProfiles; + + private Version(String version, String[] activeProfiles) { + this.version = version; + this.activeProfiles = activeProfiles; + } + + public String getVersion() { + return version; + } + + public String[] getActiveProfiles() { + return activeProfiles; + } + } +}