Merge branch 'BAEL-4095' of https://github.com/umangbudhwar/tutorials into BAEL-4095

This commit is contained in:
Umang Budhwar 2020-09-01 19:44:01 +05:30
commit 9aae16fb44
74 changed files with 1326 additions and 151 deletions

View File

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
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">
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">
<modelVersion>4.0.0</modelVersion>
<artifactId>cdi</artifactId>
<version>1.0-SNAPSHOT</version>
@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
@ -26,28 +26,22 @@
<artifactId>weld-se-core</artifactId>
<version>${weld-se-core.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -61,7 +55,6 @@
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<assertj-core.version>3.10.0</assertj-core.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties>
</project>

View File

@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
copyList.add(4);
}
}

View File

@ -30,5 +30,4 @@
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
</project>

View File

@ -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
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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<Object[]> 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);
}
}

View File

@ -1,3 +0,0 @@
### Relevant Article:
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

View File

@ -1,3 +1,4 @@
rootProject.name='gradle-5-articles'
include 'java-exec'
include 'unused-dependencies'
include 'unused-dependencies'
include 'source-sets'

1
gradle-5/source-sets/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -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]
}
}

View File

@ -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<String> someStrings = ImmutableList.of("Baeldung", "is", "cool");
assertThat(underTest.getUser(), is("lorem"));
assertThat(underTest.getPassword(), is("ipsum"));
assertThat(someStrings.size(), is(3));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.main;
public class SourceSetsMain {
public static void main(String[] args) {
System.out.println("Hell..oh...world!");
}
}

View File

@ -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;
}
}

View File

@ -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"));
}
}

View File

@ -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<Smurf> findAll() {

View File

@ -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;

View File

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-spring-4</relativePath>
<relativePath>../../parent-spring-5</relativePath>
</parent>
<dependencies>

View File

@ -27,6 +27,7 @@
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${version.derby}</version>
<scope>provided</scope>
</dependency>
<!-- For tests -->
@ -70,27 +71,16 @@
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>${version.liberty-maven-plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${version.maven-dependency-plugin}</version>
<executions>
<execution>
<id>copy-derby-dependency</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeArtifactIds>derby</includeArtifactIds>
<outputDirectory>${project.build.directory}/liberty/wlp/usr/shared/resources/</outputDirectory>
<systemPropertyVariables>
<liberty.test.port>${testServerHttpPort}</liberty.test.port>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
<configuration>
<copyDependencies>
<location>${project.build.directory}/liberty/wlp/usr/shared/resources/</location>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${version.derby}</version>
</dependency>
</copyDependencies>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -112,8 +102,7 @@
<version.jakarta.jakartaee-web-api>8.0.0</version.jakarta.jakartaee-web-api>
<version.microprofile>3.2</version.microprofile>
<version.derby>10.14.2.0</version.derby>
<version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
<version.maven-dependency-plugin>2.10</version.maven-dependency-plugin>
<version.liberty-maven-plugin>3.3-M3</version.liberty-maven-plugin>
<version.maven-war-plugin>3.2.3</version.maven-war-plugin>
<version.junit>4.12</version.junit>
<version.yasson>1.0.5</version.yasson>

View File

@ -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;
}
}

View File

@ -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<Student> likes;
private Set<Student> likes = new HashSet<>();
@OneToMany(mappedBy = "course")
private Set<CourseRating> ratings;
private Set<CourseRating> ratings = new HashSet<>();
@OneToMany(mappedBy = "course")
private Set<CourseRegistration> registrations;
private Set<CourseRegistration> 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<Student> getLikes() {
return likes;
}
public void setLikes(Set<Student> likes) {
this.likes = likes;
}
public Set<CourseRating> getRatings() {
return ratings;
}
public void setRatings(Set<CourseRating> ratings) {
this.ratings = ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
public void setRegistrations(Set<CourseRegistration> registrations) {
this.registrations = registrations;
}
@Override
public int hashCode() {
final int prime = 31;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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<Course> likedCourses;
private Set<Course> likedCourses = new HashSet<>();
@OneToMany(mappedBy = "student")
private Set<CourseRating> ratings;
private Set<CourseRating> ratings = new HashSet<>();
@OneToMany(mappedBy = "student")
private Set<CourseRegistration> registrations;
private Set<CourseRegistration> 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<Course> getLikedCourses() {
return likedCourses;
}
public void setLikedCourses(Set<Course> likedCourses) {
this.likedCourses = likedCourses;
}
public Set<CourseRating> getRatings() {
return ratings;
}
public void setRatings(Set<CourseRating> ratings) {
this.ratings = ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
public void setRegistrations(Set<CourseRegistration> registrations) {
this.registrations = registrations;
}
@Override
public int hashCode() {
final int prime = 31;

View File

@ -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));
}
}

View File

@ -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();
}

View File

@ -701,6 +701,7 @@
<module>spring-rest-compress</module>
<module>spring-rest-hal-browser</module>
<module>spring-rest-http</module>
<module>spring-rest-http-2</module>
<module>spring-rest-query-language</module>
<module>spring-rest-shell</module>
<module>spring-rest-simple</module>

View File

@ -30,9 +30,48 @@
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
<version>${quarkus.version}</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
<version>${quarkus.version}</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2</artifactId>
<version>${quarkus.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<version>${quarkus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<version>${quarkus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-h2</artifactId>
<version>${quarkus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -117,7 +156,8 @@
<properties>
<surefire-plugin.version>2.22.0</surefire-plugin.version>
<quarkus.version>0.15.0</quarkus.version>
<quarkus.version>1.7.0.Final</quarkus.version>
<junit-jupiter.version>5.6.0</junit-jupiter.version>
</properties>
</project>

View File

@ -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<Book> findBooks(@QueryParam("query") String query) {
return libraryService.find(query);
}
}

View File

@ -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;
}

View File

@ -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<Book> {
public Stream<Book> findBy(String query) {
return find("author like :query or title like :query", with("query", "%"+query+"%")).stream();
}
}

View File

@ -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<Book> find(String query) {
if (query == null) {
return bookRepository.findAll().stream().collect(toSet());
}
return bookRepository.findBy(query).collect(toSet());
}
}

View File

@ -1,3 +1,12 @@
# Configuration file
# key = value
greeting=Good morning
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

View File

@ -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"));
}
}

View File

@ -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);
}
}

View File

@ -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"));
}
}

View File

@ -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");
}
}

View File

@ -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"));
}
}

View File

@ -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.

View File

@ -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 {
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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<String, String> getConfigOverrides() {
return Collections.singletonMap("quarkus.resteasy.path", "/custom");
}
@Override
public Set<Class<?>> getEnabledAlternatives() {
return Collections.singleton(TestBookRepository.class);
}
@Override
public String getConfigProfile() {
return "custom-profile";
}
}

View File

@ -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 {
}

View File

@ -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"));
}
}

View File

@ -1,2 +1,2 @@
# Files #
*.log
*.log

View File

@ -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);
}
}

View File

@ -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<String> getResult(ServerHttpRequest request) {
return Mono.defer(() -> Mono.just("Result is ready!"))
.delaySubscription(Duration.ofMillis(500));
}
}

View File

@ -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<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
return Mono
.delay(Duration.ofMillis(200))
.then(
webFilterChain.filter(serverWebExchange)
);
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.conditionalonproperty.service;
public class EmailNotification implements NotificationSender {
@Override
public String send(String message) {
return "Email Notification: " + message;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.conditionalonproperty.service;
public interface NotificationSender {
String send(String message);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.conditionalonproperty.service;
public class SmsNotification implements NotificationSender {
@Override
public String send(String message) {
return "SMS notification: " + message;
}
}

View File

@ -1,2 +1,4 @@
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto = update
notification.service=email

View File

@ -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");
});
}
}

View File

@ -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<String> getResultAsyc(HttpServletRequest request) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture("Result is ready!");
}
}

View File

@ -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() {
}
}

View File

@ -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);
}
}

View File

@ -49,6 +49,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
@ -99,24 +103,7 @@
<!-- Spring Fox 2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${spring.fox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${spring.fox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>${spring.fox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<artifactId>springfox-boot-starter</artifactId>
<version>${spring.fox.version}</version>
</dependency>

View File

@ -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();
}

View File

@ -41,7 +41,7 @@
<properties>
<aws-sdk.version>1.11.632</aws-sdk.version>
<spring-cloud-stream-kinesis-binder.version>1.2.1.RELEASE</spring-cloud-stream-kinesis-binder.version>
<spring-cloud-stream-kinesis-binder.version>2.0.2.RELEASE</spring-cloud-stream-kinesis-binder.version>
<spring-cloud-stream-test.version>2.2.1.RELEASE</spring-cloud-stream-test.version>
</properties>

View File

@ -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);

View File

@ -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. ");
}
}

View File

@ -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");
}

View File

@ -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:

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project 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">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-rest-http-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-rest-http-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
</dependencies>
<properties>
<swagger2.version>2.9.2</swagger2.version>
</properties>
</project>

View File

@ -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);
}
}

View File

@ -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/");
}
}

View File

@ -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;
}
}
}