diff --git a/annotations/readme.md b/annotations/readme.md index 8b13789179..2b052803e6 100644 --- a/annotations/readme.md +++ b/annotations/readme.md @@ -1 +1,2 @@ - +### Relevant Articles: +- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder) diff --git a/apache-cxf/cxf-introduction/README.md b/apache-cxf/cxf-introduction/README.md new file mode 100644 index 0000000000..9a076524b7 --- /dev/null +++ b/apache-cxf/cxf-introduction/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf) diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 232a4f0089..0902bd690e 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -11,6 +11,7 @@ 3.1.6 + 2.19.1 @@ -26,7 +27,7 @@ 2.19.1 - **/StudentTest.java + **/*LiveTest.java @@ -44,4 +45,5 @@ ${cxf.version} + diff --git a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java similarity index 65% rename from apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java rename to apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java index e1e5b60ec3..60fc0a10e7 100644 --- a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java +++ b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java @@ -2,20 +2,16 @@ package com.baeldung.cxf.introduction; import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; - import java.util.Map; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPBinding; -import com.baeldung.cxf.introduction.Baeldung; -import com.baeldung.cxf.introduction.Student; -import com.baeldung.cxf.introduction.StudentImpl; +import org.junit.Before; +import org.junit.Test; -public class StudentTest { +public class StudentLiveTest { private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung"); private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort"); @@ -25,7 +21,7 @@ public class StudentTest { { service = Service.create(SERVICE_NAME); - String endpointAddress = "http://localhost:8080/baeldung"; + final String endpointAddress = "http://localhost:8080/baeldung"; service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); } @@ -37,28 +33,28 @@ public class StudentTest { @Test public void whenUsingHelloMethod_thenCorrect() { - String endpointResponse = baeldungProxy.hello("Baeldung"); - String localResponse = baeldungImpl.hello("Baeldung"); + final String endpointResponse = baeldungProxy.hello("Baeldung"); + final String localResponse = baeldungImpl.hello("Baeldung"); assertEquals(localResponse, endpointResponse); } @Test public void whenUsingHelloStudentMethod_thenCorrect() { - Student student = new StudentImpl("John Doe"); - String endpointResponse = baeldungProxy.helloStudent(student); - String localResponse = baeldungImpl.helloStudent(student); + final Student student = new StudentImpl("John Doe"); + final String endpointResponse = baeldungProxy.helloStudent(student); + final String localResponse = baeldungImpl.helloStudent(student); assertEquals(localResponse, endpointResponse); } @Test public void usingGetStudentsMethod_thenCorrect() { - Student student1 = new StudentImpl("Adam"); + final Student student1 = new StudentImpl("Adam"); baeldungProxy.helloStudent(student1); - Student student2 = new StudentImpl("Eve"); + final Student student2 = new StudentImpl("Eve"); baeldungProxy.helloStudent(student2); - - Map students = baeldungProxy.getStudents(); + + final Map students = baeldungProxy.getStudents(); assertEquals("Adam", students.get(1).getName()); assertEquals("Eve", students.get(2).getName()); } diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml new file mode 100644 index 0000000000..b3a81aef82 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + cxf-jaxrs-implementation + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + UTF-8 + 3.1.7 + 4.5.2 + 2.19.1 + + + + + org.codehaus.mojo + exec-maven-plugin + + com.baeldung.cxf.jaxrs.implementation.RestfulServer + + + + maven-surefire-plugin + 2.19.1 + + + **/*LiveTest.java + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java new file mode 100644 index 0000000000..9dd63cf3ac --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java @@ -0,0 +1,72 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Path("baeldung") +@Produces("text/xml") +public class Baeldung { + private Map courses = new HashMap<>(); + + { + Student student1 = new Student(); + Student student2 = new Student(); + student1.setId(1); + student1.setName("Student A"); + student2.setId(2); + student2.setName("Student B"); + + List course1Students = new ArrayList<>(); + course1Students.add(student1); + course1Students.add(student2); + + Course course1 = new Course(); + Course course2 = new Course(); + course1.setId(1); + course1.setName("REST with Spring"); + course1.setStudents(course1Students); + course2.setId(2); + course2.setName("Learn Spring Security"); + + courses.put(1, course1); + courses.put(2, course2); + } + + @GET + @Path("courses/{courseId}") + public Course getCourse(@PathParam("courseId") int courseId) { + return findById(courseId); + } + + @PUT + @Path("courses/{courseId}") + public Response updateCourse(@PathParam("courseId") int courseId, Course course) { + Course existingCourse = findById(courseId); + if (existingCourse == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + if (existingCourse.equals(course)) { + return Response.notModified().build(); + } + courses.put(courseId, course); + return Response.ok().build(); + } + + @Path("courses/{courseId}/students") + public Course pathToStudent(@PathParam("courseId") int courseId) { + return findById(courseId); + } + + private Course findById(int id) { + for (Map.Entry course : courses.entrySet()) { + if (course.getKey() == id) { + return course.getValue(); + } + } + return null; + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java new file mode 100644 index 0000000000..dba9b9c661 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -0,0 +1,86 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.xml.bind.annotation.XmlRootElement; + +import java.util.ArrayList; +import java.util.List; + +@XmlRootElement(name = "Course") +public class Course { + private int id; + private String name; + private List students = new ArrayList<>(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } + + @GET + @Path("{studentId}") + public Student getStudent(@PathParam("studentId") int studentId) { + return findById(studentId); + } + + @POST + public Response createStudent(Student student) { + for (Student element : students) { + if (element.getId() == student.getId()) { + return Response.status(Response.Status.CONFLICT).build(); + } + } + students.add(student); + return Response.ok(student).build(); + } + + @DELETE + @Path("{studentId}") + public Response deleteStudent(@PathParam("studentId") int studentId) { + Student student = findById(studentId); + if (student == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + students.remove(student); + return Response.ok().build(); + } + + private Student findById(int id) { + for (Student student : students) { + if (student.getId() == id) { + return student; + } + } + return null; + } + + @Override + public int hashCode() { + return id + name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName())); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java new file mode 100644 index 0000000000..bb35bab3f8 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -0,0 +1,21 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; +import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; + +public class RestfulServer { + public static void main(String args[]) throws Exception { + JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean(); + factoryBean.setResourceClasses(Baeldung.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung())); + factoryBean.setAddress("http://localhost:8080/"); + Server server = factoryBean.create(); + + System.out.println("Server ready..."); + Thread.sleep(60 * 1000); + System.out.println("Server exiting"); + server.destroy(); + System.exit(0); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java new file mode 100644 index 0000000000..bd3dad0f5e --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java @@ -0,0 +1,35 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Student") +public class Student { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return id + name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName())); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml new file mode 100644 index 0000000000..097cf2ce58 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml @@ -0,0 +1,4 @@ + + 2 + Apache CXF Support for RESTful + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml new file mode 100644 index 0000000000..7d083dbdc9 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml @@ -0,0 +1,4 @@ + + 2 + Student B + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml new file mode 100644 index 0000000000..068c9dae4b --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml @@ -0,0 +1,4 @@ + + 3 + Student C + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml new file mode 100644 index 0000000000..465c337745 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml @@ -0,0 +1,4 @@ + + 3 + Apache CXF Support for RESTful + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml new file mode 100644 index 0000000000..5936fdc094 --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml @@ -0,0 +1,4 @@ + + 1 + REST with Spring + \ No newline at end of file diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java new file mode 100644 index 0000000000..29c34ae16b --- /dev/null +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java @@ -0,0 +1,130 @@ +package com.baeldung.cxf.jaxrs.implementation; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; + +import javax.xml.bind.JAXB; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ServiceLiveTest { + private static final String BASE_URL = "http://localhost:8080/baeldung/courses/"; + private static CloseableHttpClient client; + + @BeforeClass + public static void createClient() { + client = HttpClients.createDefault(); + } + + @AfterClass + public static void closeClient() throws IOException { + client.close(); + } + + @Test + public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException { + final HttpPut httpPut = new HttpPut(BASE_URL + "3"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + final HttpResponse response = client.execute(httpPut); + assertEquals(404, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException { + final HttpPut httpPut = new HttpPut(BASE_URL + "1"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + final HttpResponse response = client.execute(httpPut); + assertEquals(304, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException { + final HttpPut httpPut = new HttpPut(BASE_URL + "2"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml"); + httpPut.setEntity(new InputStreamEntity(resourceStream)); + httpPut.setHeader("Content-Type", "text/xml"); + + final HttpResponse response = client.execute(httpPut); + assertEquals(200, response.getStatusLine().getStatusCode()); + + final Course course = getCourse(2); + assertEquals(2, course.getId()); + assertEquals("Apache CXF Support for RESTful", course.getName()); + } + + @Test + public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException { + final HttpPost httpPost = new HttpPost(BASE_URL + "1/students"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml"); + httpPost.setEntity(new InputStreamEntity(resourceStream)); + httpPost.setHeader("Content-Type", "text/xml"); + + final HttpResponse response = client.execute(httpPost); + assertEquals(409, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException { + final HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); + final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml"); + httpPost.setEntity(new InputStreamEntity(resourceStream)); + httpPost.setHeader("Content-Type", "text/xml"); + + final HttpResponse response = client.execute(httpPost); + assertEquals(200, response.getStatusLine().getStatusCode()); + + final Student student = getStudent(2, 3); + assertEquals(3, student.getId()); + assertEquals("Student C", student.getName()); + } + + @Test + public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException { + final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3"); + final HttpResponse response = client.execute(httpDelete); + assertEquals(404, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException { + final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); + final HttpResponse response = client.execute(httpDelete); + assertEquals(200, response.getStatusLine().getStatusCode()); + + final Course course = getCourse(1); + assertEquals(1, course.getStudents().size()); + assertEquals(2, course.getStudents().get(0).getId()); + assertEquals("Student B", course.getStudents().get(0).getName()); + } + + private Course getCourse(int courseOrder) throws IOException { + final URL url = new URL(BASE_URL + courseOrder); + final InputStream input = url.openStream(); + return JAXB.unmarshal(new InputStreamReader(input), Course.class); + } + + private Student getStudent(int courseOrder, int studentOrder) throws IOException { + final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); + final InputStream input = url.openStream(); + return JAXB.unmarshal(new InputStreamReader(input), Student.class); + } +} \ No newline at end of file diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index 85e68300f0..8f1dee965a 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -51,7 +51,7 @@ ${surefire.version} - StudentTest.java + **/*LiveTest.java @@ -60,7 +60,7 @@ - integration + live diff --git a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java similarity index 97% rename from apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java rename to apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java index 7466944e04..80a8f6c3b8 100644 --- a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java +++ b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -public class StudentTest { +public class StudentLiveTest { private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class); private Baeldung baeldungProxy = (Baeldung) context.getBean("client"); diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 022fc59f9b..af7949bb6c 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -8,6 +8,7 @@ cxf-introduction cxf-spring + cxf-jaxrs-implementation diff --git a/assertj/README.md b/assertj/README.md new file mode 100644 index 0000000000..86eff05057 --- /dev/null +++ b/assertj/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [AssertJ’s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features) +- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava) diff --git a/assertj/pom.xml b/assertj/pom.xml index 421afd40a5..df55ebba4b 100644 --- a/assertj/pom.xml +++ b/assertj/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -9,11 +8,18 @@ 1.0.0-SNAPSHOT + com.google.guava guava - 19.0 + ${guava.version} + + org.assertj + assertj-guava + 3.0.0 + + junit junit @@ -26,11 +32,7 @@ 3.5.1 test - - org.assertj - assertj-guava - 3.0.0 - + @@ -46,4 +48,9 @@ + + + 19.0 + + \ No newline at end of file diff --git a/autovalue/README.md b/autovalue/README.md new file mode 100644 index 0000000000..2385e82847 --- /dev/null +++ b/autovalue/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) diff --git a/autovalue-tutorial/pom.xml b/autovalue/pom.xml similarity index 100% rename from autovalue-tutorial/pom.xml rename to autovalue/pom.xml diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java rename to autovalue/src/main/java/com/baeldung/autovalue/Foo.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java diff --git a/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java similarity index 100% rename from autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java rename to autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java diff --git a/cdi/README.md b/cdi/README.md new file mode 100644 index 0000000000..a27c35772a --- /dev/null +++ b/cdi/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) diff --git a/cdi/pom.xml b/cdi/pom.xml index b771857938..30dd167fa8 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -45,8 +45,60 @@ + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + 4.3.1.RELEASE + 2.19.1 \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java similarity index 95% rename from cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java rename to cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java index 1f3a8d83e3..cffa2256ca 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java @@ -16,7 +16,7 @@ import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class TestSpringInterceptor { +public class SpringInterceptorIntegrationTest { @Autowired SpringSuperService springSuperService; diff --git a/core-java-8/README.md b/core-java-8/README.md index c130e6bd41..a835914b4d 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,11 +11,8 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) -- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 566eb4e43a..22e3bab595 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -15,7 +15,7 @@ commons-io commons-io - 2.4 + 2.5 diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/core-java-8/src/main/java/com/baeldung/datetime/README.md new file mode 100644 index 0000000000..1e4adbb612 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/datetime/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) diff --git a/core-java-8/src/main/java/com/baeldung/enums/README.md b/core-java-8/src/main/java/com/baeldung/enums/README.md new file mode 100644 index 0000000000..6ccfa725f5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/enums/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java new file mode 100644 index 0000000000..208a23eb91 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java @@ -0,0 +1,84 @@ +package com.baeldung.encoderdecoder; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class EncoderDecoder { + + private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; + private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class); + + private String encodeValue(String value) { + String encoded = null; + try { + encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + LOGGER.error("Error encoding parameter {}", e.getMessage(), e); + } + return encoded; + } + + + private String decode(String value) { + String decoded = null; + try { + decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + LOGGER.error("Error encoding parameter {}", e.getMessage(), e); + } + return decoded; + } + + @Test + public void givenURL_whenAnalyze_thenCorrect() throws Exception { + URL url = new URL(URL); + + Assert.assertThat(url.getProtocol(), CoreMatchers.is("http")); + Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com")); + Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253")); + } + + @Test + public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception { + Map requestParams = new HashMap<>(); + requestParams.put("key1", "value 1"); + requestParams.put("key2", "value@!$2"); + requestParams.put("key3", "value%3"); + + String encodedQuery = requestParams.keySet().stream() + .map(key -> key + "=" + encodeValue(requestParams.get(key))) + .collect(Collectors.joining("&")); + String encodedURL = "http://www.baeldung.com?" + encodedQuery; + + Assert.assertThat(URL, CoreMatchers.is(encodedURL)); + } + + @Test + public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception { + URL url = new URL(URL); + String query = url.getQuery(); + + String decodedQuery = Arrays.stream(query.split("&")) + .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) + .collect(Collectors.joining("&")); + + Assert.assertEquals( + "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java index 3752fc5b7f..e21af9552a 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -102,22 +102,20 @@ public class FileOperationsTest { StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); lines.forEach(line -> data.append(line).append("\n")); + lines.close(); Assert.assertEquals(expectedData, data.toString().trim()); } private String readFromInputStream(InputStream inputStream) throws IOException { - InputStreamReader inputStreamReader = new InputStreamReader(inputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder resultStringBuilder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - resultStringBuilder.append(line); - resultStringBuilder.append("\n"); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line).append("\n"); + } } - bufferedReader.close(); - inputStreamReader.close(); - inputStream.close(); + return resultStringBuilder.toString(); } } \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java index 06d9394a5e..da9027060e 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -1,47 +1,41 @@ package com.baeldung.util; -import static org.junit.Assert.assertEquals; - -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.GregorianCalendar; - import org.junit.Test; +import java.time.*; +import java.time.temporal.ChronoField; + +import static org.junit.Assert.assertEquals; + public class CurrentDateTimeTest { + private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC")); + @Test public void shouldReturnCurrentDate() { - final LocalDate now = LocalDate.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalDate now = LocalDate.now(clock); - assertEquals("10-10-2010".length(), now.toString().length()); - assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); - assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); - assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR)); + assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(2016, now.get(ChronoField.YEAR)); } @Test public void shouldReturnCurrentTime() { - final LocalTime now = LocalTime.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalTime now = LocalTime.now(clock); - assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); - assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); - assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); } @Test public void shouldReturnCurrentTimestamp() { - final Instant now = Instant.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final Instant now = Instant.now(clock); - assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); } } diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD index 8b13789179..2f44a2336b 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/README.MD +++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD @@ -1 +1,2 @@ - +### Relevant Artiles: +- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional) diff --git a/core-java/README.md b/core-java/README.md index 23fe12465f..c18e6670ca 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -13,3 +13,12 @@ - [Java – Write to File](http://www.baeldung.com/java-write-to-file) - [Java Scanner](http://www.baeldung.com/java-scanner) - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) +- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer) +- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) +- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) +- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) +- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) +- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) diff --git a/core-java/pom.xml b/core-java/pom.xml index bce97d1148..75608b59ba 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,211 +1,321 @@ - - 4.0.0 - com.baeldung - core-java - 0.1.0-SNAPSHOT + + 4.0.0 + com.baeldung + core-java + 0.1.0-SNAPSHOT + jar - core-java + core-java - + - - - net.sourceforge.collections - collections-generic - 4.01 - - - com.google.guava - guava - ${guava.version} - + + + net.sourceforge.collections + collections-generic + 4.01 + + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-math3 - 3.3 - + + org.apache.commons + commons-math3 + 3.3 + - + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.assertj - assertj-core - ${assertj.version} - test - + + org.assertj + assertj-core + ${assertj.version} + test + - - org.testng - testng - ${testng.version} - test - + + org.testng + testng + ${testng.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - - - - commons-codec - commons-codec - 1.10 - + + org.mockito + mockito-core + ${mockito.version} + test + - + + commons-codec + commons-codec + 1.10 + - - core-java - - - src/main/resources - true - - + - + + core-java + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + - + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + - - - 4.3.11.Final - 5.1.38 + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + - - 2.7.2 + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + - - 1.7.13 - 1.1.3 + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + - - 5.1.3.Final + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + - - 19.0 - 3.4 + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + + + - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 + - 4.4.1 - 4.5 + + + 4.3.11.Final + 5.1.38 - 2.9.0 + + 2.7.8 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + + 1.7.13 + 1.1.3 - + + 5.1.3.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java new file mode 100644 index 0000000000..1c034051aa --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java @@ -0,0 +1,46 @@ +package com.baeldung.java.nio.selector; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class EchoClient { + private static SocketChannel client; + private static ByteBuffer buffer; + private static EchoClient instance; + + public static EchoClient start() { + if (instance == null) + instance = new EchoClient(); + + return instance; + } + + private EchoClient() { + try { + client = SocketChannel.open(new InetSocketAddress("localhost", 5454)); + buffer = ByteBuffer.allocate(256); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String sendMessage(String msg) { + buffer = ByteBuffer.wrap(msg.getBytes()); + String response = null; + try { + client.write(buffer); + buffer.clear(); + client.read(buffer); + response = new String(buffer.array()).trim(); + System.out.println("response=" + response); + buffer.clear(); + } catch (IOException e) { + e.printStackTrace(); + } + return response; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java new file mode 100644 index 0000000000..285d4e51fc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -0,0 +1,62 @@ +package com.baeldung.java.nio.selector; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.Iterator; +import java.util.Set; + +public class EchoServer { + + public static void main(String[] args) + + throws IOException { + Selector selector = Selector.open(); + ServerSocketChannel serverSocket = ServerSocketChannel.open(); + serverSocket.bind(new InetSocketAddress("localhost", 5454)); + serverSocket.configureBlocking(false); + serverSocket.register(selector, SelectionKey.OP_ACCEPT); + ByteBuffer buffer = ByteBuffer.allocate(256); + + while (true) { + selector.select(); + Set selectedKeys = selector.selectedKeys(); + Iterator iter = selectedKeys.iterator(); + while (iter.hasNext()) { + + SelectionKey key = iter.next(); + + if (key.isAcceptable()) { + SocketChannel client = serverSocket.accept(); + client.configureBlocking(false); + client.register(selector, SelectionKey.OP_READ); + } + + if (key.isReadable()) { + SocketChannel client = (SocketChannel) key.channel(); + client.read(buffer); + buffer.flip(); + client.write(buffer); + buffer.clear(); + } + iter.remove(); + } + } + } + + public static Process start() throws IOException, InterruptedException { + String javaHome = System.getProperty("java.home"); + String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; + String classpath = System.getProperty("java.class.path"); + String className = EchoServer.class.getCanonicalName(); + + ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); + + return builder.start(); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java new file mode 100644 index 0000000000..27fd84e374 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -0,0 +1,23 @@ +package com.baeldung.printscreen; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; + +public class Screenshot { + + private final String path; + + public Screenshot(String path) { + this.path = path; + } + + public void getScreenshot(int timeToWait) throws Exception { + Thread.sleep(timeToWait); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Robot robot = new Robot(); + BufferedImage img = robot.createScreenCapture(rectangle); + ImageIO.write(img, "jpg", new File(path)); + } +} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java similarity index 94% rename from sockets/src/main/java/com/baeldung/socket/EchoClient.java rename to core-java/src/main/java/com/baeldung/socket/EchoClient.java index e8ec97c80a..1ddf752a03 100644 --- a/sockets/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -23,8 +23,7 @@ public class EchoClient { public String sendMessage(String msg) { try { out.println(msg); - String resp = in.readLine(); - return resp; + return in.readLine(); } catch (Exception e) { return null; } diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java rename to core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/EchoServer.java rename to core-java/src/main/java/com/baeldung/socket/EchoServer.java diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java similarity index 94% rename from sockets/src/main/java/com/baeldung/socket/GreetClient.java rename to core-java/src/main/java/com/baeldung/socket/GreetClient.java index 7252827c87..21959c7469 100644 --- a/sockets/src/main/java/com/baeldung/socket/GreetClient.java +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -26,8 +26,7 @@ public class GreetClient { public String sendMessage(String msg) { try { out.println(msg); - String resp = in.readLine(); - return resp; + return in.readLine(); } catch (Exception e) { return null; } diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java similarity index 100% rename from sockets/src/main/java/com/baeldung/socket/GreetServer.java rename to core-java/src/main/java/com/baeldung/socket/GreetServer.java diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java new file mode 100644 index 0000000000..2c52a17904 --- /dev/null +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -0,0 +1,11 @@ +package org.baeldung.executable; + +import javax.swing.JOptionPane; + +public class ExecutableMavenJar { + + public static void main(String[] args) { + JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java rename to core-java/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java rename to core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java index ce878026d4..e07bcc9a8d 100644 --- a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java @@ -1,5 +1,8 @@ package com.baeldung.functionalinterface; +import com.google.common.util.concurrent.Uninterruptibles; +import org.junit.Test; + import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -10,9 +13,6 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import com.google.common.util.concurrent.Uninterruptibles; -import org.junit.Test; - import static org.junit.Assert.*; public class FunctionalInterfaceTest { diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java rename to core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java new file mode 100644 index 0000000000..d1ac6df5e4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java @@ -0,0 +1,21 @@ +package com.baeldung.java.nio.selector; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class EchoTest { + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException { + Process process = EchoServer.start(); + EchoClient client = EchoClient.start(); + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + process.destroy(); + } +} diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java new file mode 100644 index 0000000000..7e35fc3e30 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java @@ -0,0 +1,26 @@ +package com.baeldung.printscreen; + +import org.junit.After; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertTrue; + + +public class ScreenshotTest { + + private Screenshot screenshot = new Screenshot("Screenshot.jpg"); + private File file = new File("Screenshot.jpg"); + + @Test + public void testGetScreenshot() throws Exception { + screenshot.getScreenshot(2000); + assertTrue(file.exists()); + } + + @After + public void tearDown() throws Exception { + file.delete(); + } +} \ No newline at end of file diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java similarity index 75% rename from sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java rename to core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java index 19a59c211c..fcf353281d 100644 --- a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoMultiTest.java @@ -1,7 +1,6 @@ package com.baeldung.socket; -import org.junit.After; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -10,18 +9,22 @@ import static org.junit.Assert.assertEquals; public class EchoMultiTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555)); - } + private static final Integer PORT = 5555; + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT)); + Thread.sleep(500); + } @Test public void givenClient1_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); @@ -31,7 +34,7 @@ public class EchoMultiTest { @Test public void givenClient2_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); @@ -44,7 +47,7 @@ public class EchoMultiTest { @Test public void givenClient3_whenServerResponds_thenCorrect() { EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); + client.startConnection("127.0.0.1", PORT); String msg1 = client.sendMessage("hello"); String msg2 = client.sendMessage("world"); String terminate = client.sendMessage("."); @@ -53,5 +56,4 @@ public class EchoMultiTest { assertEquals(terminate, "bye"); client.stopConnection(); } - } diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/core-java/src/test/java/com/baeldung/socket/EchoTest.java similarity index 65% rename from sockets/src/test/java/com/baeldung/socket/EchoTest.java rename to core-java/src/test/java/com/baeldung/socket/EchoTest.java index 0f0c02e4d8..cb09d42f79 100644 --- a/sockets/src/test/java/com/baeldung/socket/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoTest.java @@ -2,6 +2,7 @@ package com.baeldung.socket; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -9,15 +10,19 @@ import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; public class EchoTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444)); - } + private static final Integer PORT = 4444; - EchoClient client = new EchoClient(); + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Thread.sleep(500); + } + + private EchoClient client = new EchoClient(); @Before public void init() { - client.startConnection("127.0.0.1", 4444); + client.startConnection("127.0.0.1", PORT); } @Test @@ -37,5 +42,4 @@ public class EchoTest { public void tearDown() { client.stopConnection(); } - } diff --git a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java similarity index 69% rename from sockets/src/test/java/com/baeldung/socket/GreetServerTest.java rename to core-java/src/test/java/com/baeldung/socket/GreetServerTest.java index fedc32fb39..caf56a8c76 100644 --- a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerTest.java @@ -2,6 +2,7 @@ package com.baeldung.socket; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; @@ -10,16 +11,20 @@ import static org.junit.Assert.assertEquals; public class GreetServerTest { - GreetClient client; + private GreetClient client; - { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666)); + private static final Integer PORT = 6666; + + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Thread.sleep(500); } @Before public void init() { client = new GreetClient(); - client.startConnection("127.0.0.1", 6666); + client.startConnection("127.0.0.1", PORT); } diff --git a/core-java/src/test/java/org/baeldung/java/lists/README.md b/core-java/src/test/java/org/baeldung/java/lists/README.md new file mode 100644 index 0000000000..2a1e8aeeaa --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/lists/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) diff --git a/okhttp/src/test/resources/test.txt b/core-java/src/test/resources/test_md5.txt similarity index 100% rename from okhttp/src/test/resources/test.txt rename to core-java/src/test/resources/test_md5.txt diff --git a/dozer/README.md b/dozer/README.md new file mode 100644 index 0000000000..5e104d914c --- /dev/null +++ b/dozer/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Mapping With Dozer](http://www.baeldung.com/dozer) diff --git a/feign-client/README.md b/feign/README.md similarity index 66% rename from feign-client/README.md rename to feign/README.md index e6ade4d161..149f7320d9 100644 --- a/feign-client/README.md +++ b/feign/README.md @@ -3,3 +3,6 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign. [1]: https://github.com/eugenp/spring-hypermedia-api + +###Relevant Articles: +- [Intro to Feign](http://www.baeldung.com/intro-to-feign) diff --git a/feign-client/pom.xml b/feign/pom.xml similarity index 100% rename from feign-client/pom.xml rename to feign/pom.xml diff --git a/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java rename to feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java diff --git a/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java b/feign/src/main/java/com/baeldung/feign/clients/BookClient.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java rename to feign/src/main/java/com/baeldung/feign/clients/BookClient.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/Book.java b/feign/src/main/java/com/baeldung/feign/models/Book.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/Book.java rename to feign/src/main/java/com/baeldung/feign/models/Book.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java b/feign/src/main/java/com/baeldung/feign/models/BookResource.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/BookResource.java rename to feign/src/main/java/com/baeldung/feign/models/BookResource.java diff --git a/feign-client/src/main/resources/log4j2.xml b/feign/src/main/resources/log4j2.xml similarity index 100% rename from feign-client/src/main/resources/log4j2.xml rename to feign/src/main/resources/log4j2.xml diff --git a/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java similarity index 100% rename from feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java rename to feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java diff --git a/flyway-migration/README.MD b/flyway-migration/README.MD deleted file mode 100644 index 8b13789179..0000000000 --- a/flyway-migration/README.MD +++ /dev/null @@ -1 +0,0 @@ - diff --git a/flyway-migration/.gitignore b/flyway/.gitignore similarity index 92% rename from flyway-migration/.gitignore rename to flyway/.gitignore index abffe04ed2..9cdd5b9542 100644 --- a/flyway-migration/.gitignore +++ b/flyway/.gitignore @@ -1,4 +1,4 @@ -.classpath -.project -.settings +.classpath +.project +.settings target/ \ No newline at end of file diff --git a/flyway/README.MD b/flyway/README.MD new file mode 100644 index 0000000000..1b3f3c05ee --- /dev/null +++ b/flyway/README.MD @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway) diff --git a/flyway-migration/db/migration/V1_0__create_employee_schema.sql b/flyway/db/migration/V1_0__create_employee_schema.sql similarity index 96% rename from flyway-migration/db/migration/V1_0__create_employee_schema.sql rename to flyway/db/migration/V1_0__create_employee_schema.sql index 09408faecb..b6167bfacc 100644 --- a/flyway-migration/db/migration/V1_0__create_employee_schema.sql +++ b/flyway/db/migration/V1_0__create_employee_schema.sql @@ -1,8 +1,8 @@ -CREATE TABLE IF NOT EXISTS `employee` ( - -`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, -`name` varchar(20), -`email` varchar(50), -`date_of_birth` timestamp - +CREATE TABLE IF NOT EXISTS `employee` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20), +`email` varchar(50), +`date_of_birth` timestamp + )ENGINE=InnoDB DEFAULT CHARSET=UTF8; \ No newline at end of file diff --git a/flyway-migration/db/migration/V2_0__create_department_schema.sql b/flyway/db/migration/V2_0__create_department_schema.sql similarity index 96% rename from flyway-migration/db/migration/V2_0__create_department_schema.sql rename to flyway/db/migration/V2_0__create_department_schema.sql index 2b9d3364a5..c85cc81353 100644 --- a/flyway-migration/db/migration/V2_0__create_department_schema.sql +++ b/flyway/db/migration/V2_0__create_department_schema.sql @@ -1,8 +1,8 @@ -CREATE TABLE IF NOT EXISTS `department` ( - -`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, -`name` varchar(20) - -)ENGINE=InnoDB DEFAULT CHARSET=UTF8; - +CREATE TABLE IF NOT EXISTS `department` ( + +`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, +`name` varchar(20) + +)ENGINE=InnoDB DEFAULT CHARSET=UTF8; + ALTER TABLE `employee` ADD `dept_id` int AFTER `email`; \ No newline at end of file diff --git a/flyway-migration/myFlywayConfig.properties b/flyway/myFlywayConfig.properties similarity index 97% rename from flyway-migration/myFlywayConfig.properties rename to flyway/myFlywayConfig.properties index 22f3afefd3..8bb102930a 100644 --- a/flyway-migration/myFlywayConfig.properties +++ b/flyway/myFlywayConfig.properties @@ -1,5 +1,5 @@ -flyway.user=root -flyway.password=mysql -flyway.schemas=app-db -flyway.url=jdbc:mysql://localhost:3306/ +flyway.user=root +flyway.password=mysql +flyway.schemas=app-db +flyway.url=jdbc:mysql://localhost:3306/ flyway.locations=filesystem:db/migration \ No newline at end of file diff --git a/flyway-migration/pom.xml b/flyway/pom.xml similarity index 91% rename from flyway-migration/pom.xml rename to flyway/pom.xml index 6e9d683a0e..d53bc7dc41 100644 --- a/flyway-migration/pom.xml +++ b/flyway/pom.xml @@ -1,34 +1,34 @@ - - 4.0.0 - com.baeldung - flyway-migration - 1.0 - flyway-migration - A sample project to demonstrate Flyway migrations - - - mysql - mysql-connector-java - 6.0.3 - - - - - - org.flywaydb - flyway-maven-plugin - 4.0.3 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - + + 4.0.0 + com.baeldung + flyway + 1.0 + flyway + A sample project to demonstrate Flyway migrations + + + mysql + mysql-connector-java + 6.0.3 + + + + + + org.flywaydb + flyway-maven-plugin + 4.0.3 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + \ No newline at end of file diff --git a/gatling/README.md b/gatling/README.md new file mode 100644 index 0000000000..5c81c4bd6a --- /dev/null +++ b/gatling/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Gatling](http://www.baeldung.com/introduction-to-gatling) diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index 5b08f6cdec..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Performance of Gson and Jackson - -Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. diff --git a/gson-jackson-performance/pom.xml b/gson-jackson-performance/pom.xml deleted file mode 100644 index 1ea43bd7fa..0000000000 --- a/gson-jackson-performance/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - 4.0.0 - - com.baeldung - gson-jackson-performance - 0.0.1-SNAPSHOT - jar - - gson-jackson-performance - http://maven.apache.org - - - UTF-8 - - - - gson-jackson-performance - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - - - - - com.google.code.gson - gson - 2.5 - - - - com.fasterxml.jackson.core - jackson-databind - 2.7.1-1 - - - - junit - junit - 3.8.1 - test - - - - log4j - log4j - 1.2.17 - - - - - - - diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java deleted file mode 100644 index b69d306edf..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.AddressDetails; -import com.baeldung.pojo.complex.ContactDetails; -import com.baeldung.pojo.complex.CustomerAddressDetails; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -/** - * - * This class is responsible for generating data for complex type object - */ - -public class ComplexDataGeneration { - - public static CustomerPortfolioComplex generateData() { - List customerAddressDetailsList = new ArrayList(); - for (int i = 0; i < 600000; i++) { - CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails(); - customerAddressDetails.setAge(20); - customerAddressDetails.setFirstName(Utility.generateRandomName()); - customerAddressDetails.setLastName(Utility.generateRandomName()); - - List addressDetailsList = new ArrayList(); - customerAddressDetails.setAddressDetails(addressDetailsList); - - for (int j = 0; j < 2; j++) { - AddressDetails addressDetails = new AddressDetails(); - addressDetails.setZipcode(Utility.generateRandomZip()); - addressDetails.setAddress(Utility.generateRandomAddress()); - - List contactDetailsList = new ArrayList(); - addressDetails.setContactDetails(contactDetailsList); - - for (int k = 0; k < 2; k++) { - ContactDetails contactDetails = new ContactDetails(); - contactDetails.setLandline(Utility.generateRandomPhone()); - contactDetails.setMobile(Utility.generateRandomPhone()); - contactDetailsList.add(contactDetails); - contactDetails = null; - } - - addressDetailsList.add(addressDetails); - addressDetails = null; - contactDetailsList = null; - } - customerAddressDetailsList.add(customerAddressDetails); - customerAddressDetails = null; - - if (i % 6000 == 0) { - Runtime.getRuntime().gc(); - } - } - - CustomerPortfolioComplex customerPortfolioComplex = new CustomerPortfolioComplex(); - customerPortfolioComplex.setCustomerAddressDetailsList(customerAddressDetailsList); - customerAddressDetailsList = null; - return customerPortfolioComplex; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java deleted file mode 100644 index b97893e8f1..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.complex; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Complex type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataGson { - - private static final Logger logger = Logger.getLogger(ComplexDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = gson.fromJson(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java deleted file mode 100644 index 07a210fb37..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.complex; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.complex.CustomerPortfolioComplex; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Complex type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class ComplexDataJackson { - - private static final Logger logger = Logger.getLogger(ComplexDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioComplex); - logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) - throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioComplex); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioComplex customerPortfolioComplex = mapper.readValue(jsonStr , CustomerPortfolioComplex.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioComplex = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java deleted file mode 100644 index 1e186adc72..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.Customer; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -/** - * - * This class is responsible for generating data for simple type object - */ - -public class SimpleDataGeneration { - - public static CustomerPortfolioSimple generateData() { - List customerList = new ArrayList(); - for (int i = 0; i < 1; i++) { - Customer customer = new Customer(); - customer.setAge(20); - customer.setFirstName(Utility.generateRandomName()); - customer.setLastName(Utility.generateRandomName()); - - customerList.add(customer); - customer = null; - - } - - CustomerPortfolioSimple customerPortfolioSimple = new CustomerPortfolioSimple(); - customerPortfolioSimple.setCustomerLists(customerList); - customerList = null; - return customerPortfolioSimple; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java deleted file mode 100644 index b190313462..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.data.simple; - -import java.util.Map; - -import org.apache.log4j.Logger; -import com.baeldung.data.utility.Utility; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.google.gson.Gson; - -/** - * - * This class is responsible for performing functions for Simple type - * GSON like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataGson { - - private static final Logger logger = Logger.getLogger(SimpleDataGson.class); - - static Gson gson = new Gson(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - String jsonStr = null; - int j = 5; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Gson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = gson.toJson(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) { - long startParsTime = System.nanoTime(); - Map parsedMap = gson.fromJson(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - - } - - private static void parseJsonToActualObject(String jsonStr) { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = gson.fromJson(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java deleted file mode 100644 index 9330333604..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.data.simple; - -import java.io.IOException; -import java.util.Map; - -import com.baeldung.data.utility.Utility; -import org.apache.log4j.Logger; -import com.baeldung.pojo.simple.CustomerPortfolioSimple; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * This class is responsible for performing functions for Simple type - * Jackson like - * Java to Json - * Json to Map - * Json to Java Object - */ - -public class SimpleDataJackson { - - private static final Logger logger = Logger.getLogger(SimpleDataJackson.class); - - static ObjectMapper mapper = new ObjectMapper(); - - static long generateJsonAvgTime = 0L; - - static long parseJsonToMapAvgTime = 0L; - - static long parseJsonToActualObjectAvgTime = 0L; - - public static void main(String[] args) throws IOException { - CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData(); - int j = 50; - for (int i = 0; i < j; i++) { - logger.info("-------Round " + (i + 1)); - String jsonStr = generateJson(customerPortfolioSimple); - logger.info("Size of Simple content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length)); - logger.info("--------------------------------------------------------------------------"); - - parseJsonToMap(jsonStr); - parseJsonToActualObject(jsonStr); - jsonStr = null; - } - - generateJsonAvgTime = generateJsonAvgTime / j; - parseJsonToMapAvgTime = parseJsonToMapAvgTime / j; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j; - - logger.info("--------------------------------------------------------------------------"); - logger.info("Average Time to Generate JSON : " + generateJsonAvgTime); - logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime); - logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime); - logger.info("--------------------------------------------------------------------------"); - } - - private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) throws JsonProcessingException { - Runtime.getRuntime().gc(); - long startParsTime = System.nanoTime(); - String json = mapper.writeValueAsString(customerPortfolioSimple); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - generateJsonAvgTime = generateJsonAvgTime + elapsedTime; - logger.info("Json Generation Time(ms):: " + elapsedTime); - return json; - } - - private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException { - long startParsTime = System.nanoTime(); - Map parsedMap = mapper.readValue(jsonStr , Map.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime; - logger.info("Generating Map from json Time(ms):: " + elapsedTime); - logger.info("--------------------------------------------------------------------------"); - parsedMap = null; - Runtime.getRuntime().gc(); - } - - private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException , - IOException { - long startParsTime = System.nanoTime(); - CustomerPortfolioSimple customerPortfolioSimple = mapper.readValue(jsonStr , CustomerPortfolioSimple.class); - long endParsTime = System.nanoTime(); - long elapsedTime = endParsTime - startParsTime; - parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime; - logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime); - customerPortfolioSimple = null; - Runtime.getRuntime().gc(); - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java deleted file mode 100644 index 8b0c402e47..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.data.utility; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.Random; - -public class Utility { - - public static String generateRandomName() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomAddress() { - char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 30; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomZip() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 8; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String generateRandomPhone() { - char[] chars = "1234567890".toCharArray(); - StringBuilder sb = new StringBuilder(); - Random random = new Random(); - for (int i = 0; i < 10; i++) { - char c = chars[random.nextInt(chars.length)]; - sb.append(c); - } - return sb.toString(); - } - - public static String readFile(String fileName , Class clazz) throws IOException { - String dir = clazz.getResource("/").getFile(); - dir = dir + "/" + fileName; - - BufferedReader br = new BufferedReader(new FileReader(dir)); - try { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append(System.lineSeparator()); - line = br.readLine(); - } - return sb.toString(); - } finally { - br.close(); - } - } - - public static String bytesIntoMB(long bytes) { - long kilobyte = 1024; - long megabyte = kilobyte * 1024; - - if ((bytes >= 0) && (bytes < kilobyte)) { - return bytes + " B"; - - } else if ((bytes >= kilobyte) && (bytes < megabyte)) { - return (bytes / kilobyte) + " KB"; - - } else if ((bytes >= megabyte)) { - return (bytes / megabyte) + " MB"; - } - - return null; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java deleted file mode 100644 index 79725a97bd..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class AddressDetails { - - private String address; - - private String zipcode; - - private List contactDetails; - - public String getZipcode() { - return zipcode; - } - - public void setZipcode(String zipcode) { - this.zipcode = zipcode; - } - - public List getContactDetails() { - return contactDetails; - } - - public void setContactDetails(List contactDetails) { - this.contactDetails = contactDetails; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java deleted file mode 100644 index 164fe3f470..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.pojo.complex; - -public class ContactDetails { - - private String mobile; - - private String landline; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java deleted file mode 100644 index 9bc5951716..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -import com.baeldung.pojo.simple.Customer; - -public class CustomerAddressDetails extends Customer { - - private List addressDetails; - - public List getAddressDetails() { - return addressDetails; - } - - public void setAddressDetails(List addressDetails) { - this.addressDetails = addressDetails; - } -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java deleted file mode 100644 index 13f9d240b8..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.pojo.complex; - -import java.util.List; - -public class CustomerPortfolioComplex { - - private List customerAddressDetailsList; - - public List getCustomerAddressDetailsList() { - return customerAddressDetailsList; - } - - public void setCustomerAddressDetailsList(List customerAddressDetailsList) { - this.customerAddressDetailsList = customerAddressDetailsList; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java deleted file mode 100644 index 3d5668f85a..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.pojo.simple; - - -public class Customer { - - private String firstName; - - private String lastName; - - private int age; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java deleted file mode 100644 index 7cb684813c..0000000000 --- a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.pojo.simple; - -import java.util.List; - -public class CustomerPortfolioSimple { - - private List customerLists; - - public List getCustomerLists() { - return customerLists; - } - - public void setCustomerLists(List customerLists) { - this.customerLists = customerLists; - } -} diff --git a/gson-jackson-performance/src/main/resources/log4j.properties b/gson-jackson-performance/src/main/resources/log4j.properties deleted file mode 100644 index 371cbc9048..0000000000 --- a/gson-jackson-performance/src/main/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Root logger option -log4j.rootLogger=DEBUG, file - -# Redirect log messages to console -# log4j.appender.stdout=org.apache.log4j.ConsoleAppender -# log4j.appender.stdout.Target=System.out -# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file, support file rolling. -log4j.appender.file=org.apache.log4j.RollingFileAppender -log4j.appender.file.File=log4j-application.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/gson/README.md b/gson/README.md index 67651b732e..60c80477b1 100644 --- a/gson/README.md +++ b/gson/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) +- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) diff --git a/gson/pom.xml b/gson/pom.xml index 4f331f6fd9..d864c289c2 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -19,7 +19,7 @@ com.google.guava guava - 18.0 + ${guava.version} commons-io diff --git a/guava/README.md b/guava/README.md index 28bcfeb912..40e7f19f41 100644 --- a/guava/README.md +++ b/guava/README.md @@ -15,3 +15,4 @@ - [Guava – Lists](http://www.baeldung.com/guava-lists) - [Guava – Sets](http://www.baeldung.com/guava-sets) - [Guava – Maps](http://www.baeldung.com/guava-maps) +- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) diff --git a/guava/src/test/java/org/baeldung/hamcrest/README.md b/guava/src/test/java/org/baeldung/hamcrest/README.md new file mode 100644 index 0000000000..7266ecda3a --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide) diff --git a/guava18/pom.xml b/guava18/pom.xml index 6002b37d74..413e9c35b8 100644 --- a/guava18/pom.xml +++ b/guava18/pom.xml @@ -1,7 +1,6 @@ - + 4.0.0 com.baeldung @@ -14,12 +13,15 @@ guava 18.0 + junit junit 4.12 + test + diff --git a/guava19/pom.xml b/guava19/pom.xml index 13f3b471f1..61fbf38575 100644 --- a/guava19/pom.xml +++ b/guava19/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.baeldung @@ -10,20 +11,23 @@ com.google.guava guava - 19.0 + ${guava.version} + junit junit 4.12 + test org.hamcrest hamcrest-all 1.3 + test - + @@ -42,4 +46,8 @@ + + 19.0 + + \ No newline at end of file diff --git a/handling-spring-static-resources/README.md b/handling-spring-static-resources/README.md new file mode 100644 index 0000000000..d8f64bc427 --- /dev/null +++ b/handling-spring-static-resources/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc) +- [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets) diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index aca069e300..6dd0c95026 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -115,6 +115,7 @@ jackson-databind ${jackson.version} + org.hibernate hibernate-validator @@ -221,8 +222,7 @@ 1.9.2.RELEASE - - 2.7.2 + 2.7.8 1.7.13 diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml new file mode 100644 index 0000000000..00960eadd2 --- /dev/null +++ b/hazelcast/pom.xml @@ -0,0 +1,77 @@ + + 4.0.0 + com.baeldung + hazelcast + 0.0.1-SNAPSHOT + hazelcast + + + + com.hazelcast + hazelcast + ${hazelcast.version} + + + + com.hazelcast + hazelcast-client + 3.7.2 + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + ch.qos.logback + logback-core + ${logback.version} + + + + + + hazelcast + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + 3.7.2 + + + 1.7.21 + 1.1.7 + + + 3.5.1 + + + \ No newline at end of file diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java new file mode 100644 index 0000000000..697e362289 --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/NativeClient.java @@ -0,0 +1,24 @@ +package com.baeldung.hazelcast.cluster; + +import java.util.Map.Entry; + +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.config.GroupConfig; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + +public class NativeClient { + + public static void main(String[] args) throws InterruptedException { + ClientConfig config = new ClientConfig(); + GroupConfig groupConfig = config.getGroupConfig(); + groupConfig.setName("dev"); + groupConfig.setPassword("dev-pass"); + HazelcastInstance hazelcastInstanceClient = HazelcastClient.newHazelcastClient(config); + IMap map = hazelcastInstanceClient.getMap("data"); + for (Entry entry : map.entrySet()) { + System.out.println(String.format("Key: %d, Value: %s", entry.getKey(), entry.getValue())); + } + } +} diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java new file mode 100644 index 0000000000..36028834a4 --- /dev/null +++ b/hazelcast/src/main/java/com/baeldung/hazelcast/cluster/ServerNode.java @@ -0,0 +1,19 @@ +package com.baeldung.hazelcast.cluster; + +import java.util.Map; + +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IdGenerator; + +public class ServerNode { + + public static void main(String[] args) { + HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); + Map map = hazelcastInstance.getMap("data"); + IdGenerator idGenerator = hazelcastInstance.getIdGenerator("newid"); + for (int i = 0; i < 10; i++) { + map.put(idGenerator.newId(), "message" + 1); + } + } +} diff --git a/hazelcast/src/main/resources/hazelcast.xml b/hazelcast/src/main/resources/hazelcast.xml new file mode 100644 index 0000000000..f29dc532b8 --- /dev/null +++ b/hazelcast/src/main/resources/hazelcast.xml @@ -0,0 +1,16 @@ + + + + 5701 + + + + + machine1 + localhost + + + + \ No newline at end of file diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml new file mode 100644 index 0000000000..8b566286b8 --- /dev/null +++ b/hazelcast/src/main/resources/logback.xml @@ -0,0 +1,18 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java similarity index 99% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index 151ed10f37..bfe1e68ebe 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -33,7 +33,7 @@ import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.junit.Test; -public class HttpAsyncClientTest { +public class HttpAsyncClientLiveTest { private static final String HOST = "http://www.google.com"; private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 952ce3af25..66b4f5cff4 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,27 +1,11 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; - import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.conn.ssl.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; @@ -29,6 +13,17 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.junit.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build @@ -42,7 +37,7 @@ public class HttpsClientSslLiveTest { // tests @Test(expected = SSLException.class) - public final void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { + public final void whenHttpsUrlIsConsumed_thenException() throws IOException { final CloseableHttpClient httpClient = HttpClientBuilder.create().build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); @@ -53,12 +48,7 @@ public class HttpsClientSslLiveTest { @SuppressWarnings("deprecation") @Test public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, sf)); @@ -75,12 +65,7 @@ public class HttpsClientSslLiveTest { @Test public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); @@ -108,4 +93,25 @@ public class HttpsClientSslLiveTest { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } + @Test + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { + + TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; + + SSLContext sslContext = null; + try { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build(); + + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + e.printStackTrace(); + } + + CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); + httpGet.setHeader("Accept", "application/xml"); + + final HttpResponse response = client.execute(httpGet); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } + } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java b/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java deleted file mode 100644 index dc1a206f0d..0000000000 --- a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.baeldung.httpclient; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.DigestScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.util.EntityUtils; -import org.junit.Ignore; -import org.junit.Test; - -public class SandboxTest { - - // original example - @Ignore - @Test - public final void whenInterestingDigestAuthScenario_then401UnAuthorized() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http"); - - // set up the credentials to run agains the server - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd")); - - // We need a first run to get a 401 to seed the digest auth - - // Make a client using those creds - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - // And make a call to the URL we are after - final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); - - // Create a context to use - final HttpClientContext context = HttpClientContext.create(); - - // Get a response from the sever (expect a 401!) - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - - // Pull out the auth header that came back from the server - final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0]; - - // Lets use a digest scheme to solve it - final DigestScheme digest = new DigestScheme(); - digest.processChallenge(challenge); - - // Make a header with the solution based upon user/password and what the digest got out of the initial 401 reponse - final Header solution = digest.authenticate(new UsernamePasswordCredentials("user", "passwd"), httpget, context); - - // Need an auth cache to use the new digest we made - final AuthCache authCache = new BasicAuthCache(); - authCache.put(targetHost, digest); - - // Add the authCache and thus solved digest to the context - context.setAuthCache(authCache); - - // Pimp up our http get with the solved header made by the digest - httpget.addHeader(solution); - - // use it! - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost); - - for (int i = 0; i < 3; i++) { - final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context); - - try { - System.out.println("----------------------------------------"); - System.out.println(responseGood.getStatusLine()); - System.out.println(EntityUtils.toString(responseGood.getEntity())); - } finally { - responseGood.close(); - } - } - } - - @Test - public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http"); - - // set up the credentials to run agains the server - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd")); - - // This endpoint need fake cookie to work properly - final CookieStore cookieStore = new BasicCookieStore(); - final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value"); - cookie.setDomain("httpbin.org"); - cookie.setPath("/"); - cookieStore.addCookie(cookie); - - // Make a client using those creds - final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build(); - - // And make a call to the URL we are after - final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); - - // Create a context to use - final HttpClientContext context = HttpClientContext.create(); - - // Get a response from the sever (401 implicitly) - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - - // HttpClient will use cached digest parameters for future requests - System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost); - - for (int i = 0; i < 3; i++) { - final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context); - - try { - System.out.println("----------------------------------------"); - System.out.println(responseGood.getStatusLine()); - assertEquals(200, responseGood.getStatusLine().getStatusCode()); - } finally { - responseGood.close(); - } - } - client.close(); - } - - // This test needs module spring-security-rest-digest-auth to be running - @Test - public final void whenWeKnowDigestParameters_thenNo401Status() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); - - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass")); - - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"); - - final HttpClientContext context = HttpClientContext.create(); - // == make it preemptive - final AuthCache authCache = new BasicAuthCache(); - final DigestScheme digestAuth = new DigestScheme(); - digestAuth.overrideParamter("realm", "Custom Realm Name"); - digestAuth.overrideParamter("nonce", "nonce value goes here"); - authCache.put(targetHost, digestAuth); - context.setAuthCache(authCache); - // == end - System.out.println("Executing The Request knowing the digest parameters ==== "); - final HttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - client.close(); - } - - // This test needs module spring-security-rest-digest-auth to be running - @Test - public final void whenDoNotKnowParameters_thenOnlyOne401() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException { - final HttpClientContext context = HttpClientContext.create(); - final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass")); - final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - - final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"); - System.out.println("Executing The Request NOT knowing the digest parameters ==== "); - final HttpResponse tempResponse = client.execute(targetHost, httpget, context); - assertEquals(200, tempResponse.getStatusLine().getStatusCode()); - - for (int i = 0; i < 3; i++) { - System.out.println("No more Challenges or 401"); - final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context); - assertEquals(200, authResponse.getStatusLine().getStatusCode()); - authResponse.close(); - } - client.close(); - } -} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 23c1fdf430..878d220f67 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -1,16 +1,8 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -23,6 +15,13 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + public class HttpClientLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -56,7 +55,7 @@ public class HttpClientLiveTest { // tests @Test(expected = ConnectTimeoutException.class) - public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException { + public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); @@ -66,20 +65,20 @@ public class HttpClientLiveTest { // tests - configs @Test - public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException { instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build(); response = instance.execute(new HttpGet(SAMPLE_URL)); } @Test - public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, "application/xml"); response = instance.execute(request); } @Test - public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws ClientProtocolException, IOException { + public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException { response = instance.execute(new HttpGet(SAMPLE_URL)); final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); @@ -89,7 +88,7 @@ public class HttpClientLiveTest { // tests - cancel request @Test - public final void whenRequestIsCanceled_thenCorrect() throws ClientProtocolException, IOException { + public final void whenRequestIsCanceled_thenCorrect() throws IOException { instance = HttpClients.custom().build(); final HttpGet request = new HttpGet(SAMPLE_URL); response = instance.execute(request); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index ff2f1cd194..22b32e7ef5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,32 +1,33 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; + public class HttpClientSandboxLiveTest { - private CloseableHttpClient client; + @Test + public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + final AuthScope authscp = new AuthScope("localhost", 8080); + credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); - private CloseableHttpResponse response; + CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - @After - public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } + final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); + CloseableHttpResponse response = client.execute(httpGet); + + System.out.println(response.getStatusLine()); try { final HttpEntity entity = response.getEntity(); @@ -39,23 +40,4 @@ public class HttpClientSandboxLiveTest { response.close(); } } - - // tests - - // simple request - response - - @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws ClientProtocolException, IOException { - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - final AuthScope authscp = new AuthScope("localhost", 8080); - credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass")); - - client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); - - final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); - response = client.execute(httpGet); - - System.out.println(response.getStatusLine()); - } - } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java similarity index 99% rename from httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index c5c960f527..e9db8c1e16 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -36,7 +36,7 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -public class HttpClientConnectionManagementTest { +public class HttpClientConnectionManagementLiveTest { private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER7 = "http://www.baeldung.com/"; diff --git a/hystrix/README.md b/hystrix/README.md new file mode 100644 index 0000000000..cc5c8a197f --- /dev/null +++ b/hystrix/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Hystrix Integration with Existing Spring Application](http://www.baeldung.com/hystrix-integration-with-spring-aop) +- [Introduction to Hystrix](http://www.baeldung.com/introduction-to-hystrix) diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 42828e1c97..54c17f1487 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -112,9 +112,54 @@ 1.8
+ + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + +
-
- + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + +
diff --git a/immutables/README.md b/immutables/README.md new file mode 100644 index 0000000000..b69a14f035 --- /dev/null +++ b/immutables/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Immutables](http://www.baeldung.com/immutables) diff --git a/jackson/README.md b/jackson/README.md index 68765de686..f48a7dc8ab 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -19,3 +19,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Jackson – Decide What Fields Get Serialized/Deserializaed](http://www.baeldung.com/jackson-field-serializable-deserializable-or-not) - [A Guide to Jackson Annotations](http://www.baeldung.com/jackson-annotations) - [Working with Tree Model Nodes in Jackson](http://www.baeldung.com/jackson-json-node-tree-model) +- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) +- [Intro to the Jackson ObjectMapper](http://www.baeldung.com/jackson-object-mapper-tutorial) +- [XML Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-xml-serialization-and-deserialization) +- [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) +- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) diff --git a/jackson/pom.xml b/jackson/pom.xml index 17b0ac507e..e795ad11a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -174,7 +174,7 @@ 5.1.38 - 2.7.2 + 2.7.8 1.7.13 diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml index 265a230eb4..92d3a8ede6 100644 --- a/java-cassandra/pom.xml +++ b/java-cassandra/pom.xml @@ -1,56 +1,36 @@ - + 4.0.0 com.baeldung cassandra-java-client 1.0.0-SNAPSHOT - - cassandra-java-client - - - UTF-8 - - - 1.7.21 - 1.1.7 - - - 1.3 - 4.12 - 1.10.19 - 6.8 - 3.5.1 - - - 3.5.1 - + + cassandra-java-client + + - 3.1.0 - - - - - + com.datastax.cassandra cassandra-driver-core ${cassandra-driver-core.version} true - + org.cassandraunit cassandra-unit 3.0.0.1 - + com.google.guava guava - 19.0 + ${guava.version} - - + + org.slf4j @@ -74,16 +54,16 @@ log4j-over-slf4j ${org.slf4j.version} - + - junit - junit - ${junit.version} - test + junit + junit + ${junit.version} + test - - - + + + java-cassandra @@ -96,7 +76,77 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + UTF-8 + + 19.0 + + + 1.7.21 + 1.1.7 + + + 1.3 + 4.12 + 1.10.19 + 6.8 + 3.5.1 + + + 3.5.1 + 2.19.1 + + + 3.1.0 + - diff --git a/jee7/README.md b/jee7/README.md new file mode 100644 index 0000000000..44ca9c2f6e --- /dev/null +++ b/jee7/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) diff --git a/jee7schedule/pom.xml b/jee7/pom.xml similarity index 100% rename from jee7schedule/pom.xml rename to jee7/pom.xml diff --git a/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java b/jee7/src/main/java/com/baeldung/timer/TimerEvent.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java rename to jee7/src/main/java/com/baeldung/timer/TimerEvent.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee7/src/main/java/com/baeldung/timer/TimerEventListener.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java rename to jee7/src/main/java/com/baeldung/timer/TimerEventListener.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java b/jee7/src/main/java/com/baeldung/timer/WorkerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java rename to jee7/src/main/java/com/baeldung/timer/WorkerBean.java diff --git a/jee7schedule/src/main/webapp/WEB-INF/beans.xml b/jee7/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jee7schedule/src/main/webapp/WEB-INF/beans.xml rename to jee7/src/main/webapp/WEB-INF/beans.xml diff --git a/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java rename to jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 24f1c5c5ab..d2a3f1cdd8 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -58,8 +58,51 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java similarity index 91% rename from jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java rename to jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java index 82138ea23e..df147232d9 100644 --- a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java +++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JJWTFunApplication.class) @WebAppConfiguration -public class DemoApplicationTests { +public class DemoApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/jpa-storedprocedure/README.md b/jpa-storedprocedure/README.md new file mode 100644 index 0000000000..39d6784d8b --- /dev/null +++ b/jpa-storedprocedure/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) diff --git a/jsf/README.md b/jsf/README.md new file mode 100644 index 0000000000..ae92ffc42f --- /dev/null +++ b/jsf/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3) +- [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language) +- [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf) diff --git a/json/README.md b/json/README.md index c47eca3e84..e217da170f 100644 --- a/json/README.md +++ b/json/README.md @@ -5,3 +5,5 @@ ### Relevant Articles: - [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java) - [A Guide to FastJson](http://www.baeldung.com/????????) +- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms) +- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath) diff --git a/junit5/REDAME.md b/junit5/REDAME.md new file mode 100644 index 0000000000..d4e30cd257 --- /dev/null +++ b/junit5/REDAME.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) diff --git a/log4j/README.md b/log4j/README.md new file mode 100644 index 0000000000..7355372f23 --- /dev/null +++ b/log4j/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) diff --git a/log4j/pom.xml b/log4j/pom.xml index 1081513dcf..ab384d4dd1 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -20,12 +20,12 @@ org.apache.logging.log4j log4j-api - 2.6 + 2.7 org.apache.logging.log4j log4j-core - 2.6 + 2.7 diff --git a/lombok/README.md b/lombok/README.md new file mode 100644 index 0000000000..4dc1c2d09d --- /dev/null +++ b/lombok/README.md @@ -0,0 +1,2 @@ +## Relevant Articles: +- [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 4159ef35c9..aaa3e95f8c 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -55,6 +55,54 @@ - - + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + diff --git a/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java similarity index 96% rename from mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java rename to mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java index a7addf33a7..31d60c0d7d 100644 --- a/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperTest.java +++ b/mapstruct/src/test/java/com/baeldung/mapper/SimpleSourceDestinationMapperIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") -public class SimpleSourceDestinationMapperTest { +public class SimpleSourceDestinationMapperIntegrationTest { @Autowired SimpleSourceDestinationMapper simpleSourceDestinationMapper; diff --git a/mockito/README.md b/mockito/README.md index 5e7cd19f78..6de2fb0c7a 100644 --- a/mockito/README.md +++ b/mockito/README.md @@ -8,3 +8,5 @@ - [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior) - [Mockito – Using Spies](http://www.baeldung.com/mockito-spy) - [Mockito – @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations) +- [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods) +- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) diff --git a/mocks/jmockit/README.md b/mocks/jmockit/README.md index db78b2a3ac..3063fdc31d 100644 --- a/mocks/jmockit/README.md +++ b/mocks/jmockit/README.md @@ -7,3 +7,4 @@ - [JMockit 101](http://www.baeldung.com/jmockit-101) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) - [JMockit Advanced Topics](http://www.baeldung.com/jmockit-advanced-topics) +- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) diff --git a/mutation-testing/README.md b/mutation-testing/README.md index 5dd60620ba..f49aeeb881 100644 --- a/mutation-testing/README.md +++ b/mutation-testing/README.md @@ -4,3 +4,5 @@ ### Relevant Articles: - [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest) +- [Intro to JaCoCo](http://www.baeldung.com/jacoco) +- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest) diff --git a/okhttp/pom.xml b/okhttp/pom.xml deleted file mode 100644 index ba5bcf9725..0000000000 --- a/okhttp/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - org.baeldung.okhttp - okhttp - 0.0.1-SNAPSHOT - - - - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - - - - junit - junit - ${junit.version} - test - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - - - - - 3.4.1 - - - 1.3 - 4.12 - - - - diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java deleted file mode 100644 index 829bafe8ef..0000000000 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.baeldung.okhttp; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.junit.Test; - -import okhttp3.Cache; -import okhttp3.Call; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class OkHttpMiscTest { - - private static final String BASE_URL = "http://localhost:8080/spring-rest"; - - //@Test - public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() - //.connectTimeout(10, TimeUnit.SECONDS) - //.writeTimeout(10, TimeUnit.SECONDS) - .readTimeout(1, TimeUnit.SECONDS) - .build(); - - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); - - Call call = client.newCall(request); - Response response = call.execute(); - response.close(); - } - - //@Test - public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException { - - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - - OkHttpClient client = new OkHttpClient(); - - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); - - final int seconds = 1; - //final int seconds = 3; - - final long startNanos = System.nanoTime(); - final Call call = client.newCall(request); - - // Schedule a job to cancel the call in 1 second. - executor.schedule(new Runnable() { - public void run() { - - System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); - call.cancel(); - System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); - } - }, seconds, TimeUnit.SECONDS); - - try { - - System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); - - } catch (IOException e) { - - System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); - } - } - - @Test - public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException { - - int cacheSize = 10 * 1024 * 1024; // 10 MiB - File cacheDirectory = new File("src/test/resources/cache"); - Cache cache = new Cache(cacheDirectory, cacheSize); - - OkHttpClient client = new OkHttpClient.Builder() - .cache(cache) - .build(); - - Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - //.cacheControl(CacheControl.FORCE_NETWORK) - //.cacheControl(CacheControl.FORCE_CACHE) - .build(); - - Response response1 = client.newCall(request).execute(); - - String responseBody1 = response1.body().string(); - - System.out.println("Response 1 response: " + response1); - System.out.println("Response 1 cache response: " + response1.cacheResponse()); - System.out.println("Response 1 network response: " + response1.networkResponse()); - System.out.println("Response 1 responseBody: " + responseBody1); - - Response response2 = client.newCall(request).execute(); - - String responseBody2 = response2.body().string(); - - System.out.println("Response 2 response: " + response2); - System.out.println("Response 2 cache response: " + response2.cacheResponse()); - System.out.println("Response 2 network response: " + response2.networkResponse()); - System.out.println("Response 2 responseBody: " + responseBody2); - } -} diff --git a/orika/README.md b/orika/README.md new file mode 100644 index 0000000000..4ed033c170 --- /dev/null +++ b/orika/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Mapping with Orika](http://www.baeldung.com/orika-mapping) diff --git a/play-framework/student-api/test/ApplicationTest.java b/play-framework/student-api/test/ApplicationTest.java index 3d7c4875aa..1133978e9a 100644 --- a/play-framework/student-api/test/ApplicationTest.java +++ b/play-framework/student-api/test/ApplicationTest.java @@ -1,45 +1,172 @@ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import play.mvc.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import model.Student; import play.test.*; -import play.data.DynamicForm; -import play.data.validation.ValidationError; -import play.data.validation.Constraints.RequiredValidator; -import play.i18n.Lang; -import play.libs.F; -import play.libs.F.*; -import play.twirl.api.Content; - import static play.test.Helpers.*; -import static org.junit.Assert.*; - - -/** - * - * Simple (JUnit) tests that can call all parts of a play app. - * If you are interested in mocking a whole application, see the wiki for more details. - * - */ -public class ApplicationTest { - - @Test - public void simpleCheck() { - int a = 1 + 1; - assertEquals(2, a); - } - - @Test - public void renderTemplate() { - Content html = views.html.index.render("Your new application is ready."); - assertEquals("text/html", html.contentType()); - assertTrue(html.body().contains("Your new application is ready.")); - } +public class ApplicationTest{ + private static final String BASE_URL = "http://localhost:9000"; + @Test +public void testInServer() throws Exception { + TestServer server = testServer(3333); + running(server, () -> { + try { + WSClient ws = play.libs.ws.WS.newClient(3333); + CompletionStage completionStage = ws.url("/").get(); + WSResponse response = completionStage.toCompletableFuture().get(); + ws.close(); + assertEquals(OK, response.getStatus()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); +} + @Test + public void whenCreatesRecord_thenCorrect() { + Student student = new Student("jody", "west", 50); + JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); + assertTrue(obj.getBoolean("isSuccessfull")); + JSONObject body = obj.getJSONObject("body"); + assertEquals(student.getAge(), body.getInt("age")); + assertEquals(student.getFirstName(), body.getString("firstName")); + assertEquals(student.getLastName(), body.getString("lastName")); + } + + @Test + public void whenDeletesCreatedRecord_thenCorrect() { + Student student = new Student("Usain", "Bolt", 25); + JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + int id = ob1.getInt("id"); + JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertTrue(obj1.getBoolean("isSuccessfull")); + makeRequest(BASE_URL + "/" + id, "DELETE", null); + JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertFalse(obj2.getBoolean("isSuccessfull")); + } + + @Test + public void whenUpdatesCreatedRecord_thenCorrect() { + Student student = new Student("john", "doe", 50); + JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + assertEquals(student.getAge(), body1.getInt("age")); + int newAge = 60; + body1.put("age", newAge); + JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); + assertFalse(student.getAge() == body2.getInt("age")); + assertTrue(newAge == body2.getInt("age")); + } + + @Test + public void whenGetsAllRecords_thenCorrect() { + Student student1 = new Student("jane", "daisy", 50); + Student student2 = new Student("john", "daniel", 60); + Student student3 = new Student("don", "mason", 55); + Student student4 = new Student("scarlet", "ohara", 90); + + makeRequest(BASE_URL, "POST", new JSONObject(student1)); + makeRequest(BASE_URL, "POST", new JSONObject(student2)); + makeRequest(BASE_URL, "POST", new JSONObject(student3)); + makeRequest(BASE_URL, "POST", new JSONObject(student4)); + + JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); + assertTrue(objects.getBoolean("isSuccessfull")); + JSONArray array = objects.getJSONArray("body"); + assertTrue(array.length() >= 4); + } + + public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { + + URL url = null; + try { + url = new URL(myUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + HttpURLConnection conn = null; + try { + + conn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + conn.setDoInput(true); + + conn.setReadTimeout(10000); + + conn.setRequestProperty("Content-Type", "application/json"); + DataOutputStream dos = null; + int respCode = 0; + String inputString = null; + try { + conn.setRequestMethod(httpMethod); + + if (Arrays.asList("POST", "PUT").contains(httpMethod)) { + String params = parameters.toString(); + + conn.setDoOutput(true); + + dos = new DataOutputStream(conn.getOutputStream()); + dos.writeBytes(params); + dos.flush(); + dos.close(); + } + respCode = conn.getResponseCode(); + if (respCode != 200 && respCode != 201) { + String error = inputStreamToString(conn.getErrorStream()); + return error; + } + inputString = inputStreamToString(conn.getInputStream()); + + } catch (IOException e) { + + e.printStackTrace(); + } + return inputString; + } + + public static String inputStreamToString(InputStream is) { + BufferedReader br = null; + StringBuilder sb = new StringBuilder(); + + String line; + try { + + br = new BufferedReader(new InputStreamReader(is)); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return sb.toString(); + + } } diff --git a/play-framework/student-api/test/IntegrationTest.java b/play-framework/student-api/test/IntegrationTest.java deleted file mode 100644 index c53c71e124..0000000000 --- a/play-framework/student-api/test/IntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -import org.junit.*; - -import play.mvc.*; -import play.test.*; - -import static play.test.Helpers.*; -import static org.junit.Assert.*; - -import static org.fluentlenium.core.filter.FilterConstructor.*; - -public class IntegrationTest { - - /** - * add your integration test here - * in this example we just check if the welcome page is being shown - */ - @Test - public void test() { - running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { - browser.goTo("http://localhost:3333"); - assertTrue(browser.pageSource().contains("Your new application is ready.")); - }); - } - -} diff --git a/pom.xml b/pom.xml index 4497d08ade..0de16500d6 100644 --- a/pom.xml +++ b/pom.xml @@ -17,8 +17,8 @@ assertj apache-cxf - autovalue-tutorial - + autovalue + cdi core-java core-java-8 @@ -26,15 +26,15 @@ dozer - dependency-injection deltaspike patterns - feign-client + feign + flyway + gson - gson-jackson-performance guava guava18 guava19 @@ -47,12 +47,12 @@ jackson javaxval jjwt - jooq-spring + jpa-storedprocedure json json-path junit5 - jee7schedule + jee7 log4j @@ -69,7 +69,6 @@ rest-assured rest-testing resteasy - okhttp spring-all spring-akka @@ -77,6 +76,7 @@ spring-autowire spring-batch spring-boot + spring-core spring-cucumber spring-data-cassandra spring-data-couchbase-2 @@ -89,8 +89,9 @@ spring-freemarker spring-hibernate3 spring-hibernate4 - spring-jpa spring-jms + spring-jooq + spring-jpa spring-katharsis spring-mockito spring-mvc-java @@ -128,6 +129,7 @@ jsf xml + xmlunit2 lombok redis diff --git a/querydsl/README.md b/querydsl/README.md new file mode 100644 index 0000000000..ef9f8f894c --- /dev/null +++ b/querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Querydsl](http://www.baeldung.com/intro-to-querydsl) diff --git a/querydsl/pom.xml b/querydsl/pom.xml index bed0cf90e5..13528526ea 100644 --- a/querydsl/pom.xml +++ b/querydsl/pom.xml @@ -20,6 +20,7 @@ 5.2.1.Final 4.1.3 1.7.21 + 2.19.1 @@ -166,7 +167,55 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java similarity index 98% rename from querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java rename to querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java index 0e5996a8c8..a666aea8da 100644 --- a/querydsl/src/test/java/org/baeldung/dao/PersonDaoTest.java +++ b/querydsl/src/test/java/org/baeldung/dao/PersonDaoIntegrationTest.java @@ -17,7 +17,7 @@ import junit.framework.Assert; @RunWith(SpringJUnit4ClassRunner.class) @Transactional @TransactionConfiguration(defaultRollback = true) -public class PersonDaoTest { +public class PersonDaoIntegrationTest { @Autowired private PersonDao personDao; diff --git a/raml/resource-types-and-traits/README.md b/raml/resource-types-and-traits/README.md new file mode 100644 index 0000000000..72e7b454d6 --- /dev/null +++ b/raml/resource-types-and-traits/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Eliminate Redundancies in RAML with Resource Types and Traits](http://www.baeldung.com/simple-raml-with-resource-types-and-traits) diff --git a/redis/src/test/java/com/baeldung/JedisTest.java b/redis/src/test/java/com/baeldung/JedisTest.java index 766fd7b5e9..582bb266aa 100644 --- a/redis/src/test/java/com/baeldung/JedisTest.java +++ b/redis/src/test/java/com/baeldung/JedisTest.java @@ -1,28 +1,15 @@ package com.baeldung; +import org.junit.*; +import redis.clients.jedis.*; +import redis.embedded.RedisServer; + import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Set; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Pipeline; -import redis.clients.jedis.Response; -import redis.clients.jedis.Transaction; -import redis.embedded.RedisServer; - -/** - * Unit test for Redis Java library - Jedis. - */ public class JedisTest { private Jedis jedis; @@ -140,9 +127,9 @@ public class JedisTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - for (String player : scores.keySet()) { + scores.keySet().forEach(player -> { jedis.zadd(key, scores.get(player), player); - } + }); Set players = jedis.zrevrange(key, 0, 1); Assert.assertEquals("PlayerThree", players.iterator().next()); diff --git a/rest-assured/README.md b/rest-assured/README.md index e69de29bb2..50f36f61eb 100644 --- a/rest-assured/README.md +++ b/rest-assured/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [A Guide to REST-assured](http://www.baeldung.com/rest-assured-tutorial) diff --git a/rest-assured/pom.xml b/rest-assured/pom.xml index 47241b18bd..e2a2af9cd9 100644 --- a/rest-assured/pom.xml +++ b/rest-assured/pom.xml @@ -1,257 +1,226 @@ - 4.0.0 - com.baeldung - rest-assured - 1.0 - rest-assured - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - - javax.servlet - javax.servlet-api - 3.1-b06 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + rest-assured + 1.0 + rest-assured - - - javax.servlet - servlet-api - 2.5 - + + + javax.servlet + javax.servlet-api + 3.1-b06 + + + javax.servlet + servlet-api + 2.5 + + + org.eclipse.jetty + jetty-security + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlet + 9.2.0.M1 + + + org.eclipse.jetty + jetty-servlets + 9.2.0.M1 + + + org.eclipse.jetty + jetty-io + 9.2.0.M1 + + + org.eclipse.jetty + jetty-http + 9.2.0.M1 + + + org.eclipse.jetty + jetty-server + 9.2.0.M1 + + + org.eclipse.jetty + jetty-util + 9.2.0.M1 + - - - org.eclipse.jetty - jetty-security - 9.2.0.M1 - + + org.slf4j + slf4j-api + 1.7.21 + - - - org.eclipse.jetty - jetty-servlet - 9.2.0.M1 - + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-log4j12 + 1.7.21 + - - - org.eclipse.jetty - jetty-servlets - 9.2.0.M1 - + + commons-logging + commons-logging + 1.2 + - - - org.eclipse.jetty - jetty-io - 9.2.0.M1 - + + org.apache.httpcomponents + httpcore + 4.4.5 + - - - org.eclipse.jetty - jetty-http - 9.2.0.M1 - + + org.apache.commons + commons-lang3 + 3.4 + + + com.github.fge + uri-template + 0.9 + + + com.googlecode.libphonenumber + libphonenumber + 7.4.5 + - - - org.eclipse.jetty - jetty-server - 9.2.0.M1 - + + javax.mail + mail + 1.4.7 + - - - org.eclipse.jetty - jetty-util - 9.2.0.M1 - + + joda-time + joda-time + 2.9.4 + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - org.slf4j - slf4j-api - 1.7.21 - + + com.github.fge + msg-simple + 1.1 + - - - log4j - log4j - 1.2.17 - - - - org.slf4j - slf4j-log4j12 - 1.7.21 - + + com.github.fge + jackson-coreutils + 1.8 + - - - - commons-logging - commons-logging - 1.2 - + + com.google.guava + guava + ${guava.version} + + + com.github.fge + btf + 1.2 + - - org.apache.httpcomponents - httpcore - 4.4.5 - + + org.apache.httpcomponents + httpclient + 4.5.2 + - - - org.apache.commons - commons-lang3 - 3.4 - + + org.codehaus.groovy + groovy-all + 2.4.7 + - - - - com.github.fge - uri-template - 0.9 - + + com.github.tomakehurst + wiremock + 2.1.7 + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + json-schema-validator + 3.0.0 + + + com.github.fge + json-schema-validator + 2.2.6 + + + com.github.fge + json-schema-core + 1.2.5 + + + junit + junit + 4.3 + test + - - - com.googlecode.libphonenumber - libphonenumber - 7.4.5 - + + org.hamcrest + hamcrest-all + 1.3 + + + commons-collections + commons-collections + 3.2.2 + - - javax.mail - mail - 1.4.7 - + - - joda-time - joda-time - 2.9.4 - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 8 + 8 + + + + - - com.fasterxml.jackson.core - jackson-annotations - 2.8.0 - + + 2.8.3 + 19.0 + - - com.fasterxml.jackson.core - jackson-databind - 2.8.0 - - - - com.fasterxml.jackson.core - jackson-core - 2.8.0 - - - - com.github.fge - msg-simple - 1.1 - - - - com.github.fge - jackson-coreutils - 1.8 - - - - - - com.google.guava - guava - 18.0 - - - com.github.fge - btf - 1.2 - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - - org.codehaus.groovy - groovy-all - 2.4.7 - - - - com.github.tomakehurst - wiremock - 2.1.7 - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - json-schema-validator - 3.0.0 - - - com.github.fge - json-schema-validator - 2.2.6 - - - com.github.fge - json-schema-core - 1.2.5 - - - junit - junit - 4.3 - test - - - - org.hamcrest - hamcrest-all - 1.3 - - - - commons-collections - commons-collections - 3.2.2 - - - diff --git a/rest-testing/README.md b/rest-testing/README.md index 54a2e98dda..5dd4e49162 100644 --- a/rest-testing/README.md +++ b/rest-testing/README.md @@ -7,3 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/) +- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) +- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml index 652f2ab601..90c160af15 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -148,15 +148,57 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*UnitTest.java + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + json + + + + + + + + - 2.7.2 + 2.7.8 1.7.13 diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java similarity index 84% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java rename to rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java index 041de592e9..f80178a43d 100644 --- a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java +++ b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java @@ -6,5 +6,5 @@ import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "classpath:Feature") -public class CucumberTest { +public class CucumberIntegrationTest { } \ No newline at end of file diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index bf5a082fba..861c0b1986 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -20,14 +20,35 @@ maven-surefire-plugin 2.19.1 - + true - Test*.java + **/*UnitTest.java + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + **/*LiveTest.java + + + + + + + + org.seleniumhq.selenium @@ -37,12 +58,12 @@ junit junit - 4.8.1 + 4.12 org.testng testng - 6.9.10 + 6.9.13.6 \ No newline at end of file diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index d8b248df81..1007bf7503 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -1,15 +1,22 @@ package main.java.com.baeldung.selenium; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumExample { private WebDriver webDriver; private String url = "http://www.baeldung.com/"; - + public SeleniumExample() { webDriver = new FirefoxDriver(); + webDriver.manage().window().maximize(); + webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); webDriver.get(url); } @@ -21,4 +28,30 @@ public class SeleniumExample { return webDriver.getTitle(); } + public void getAboutBaeldungPage() { + closeOverlay(); + clickAboutLink(); + clickAboutUsLink(); + } + + private void closeOverlay() { + List webElementList = webDriver.findElements(By.tagName("a")); + if (webElementList != null && !webElementList.isEmpty()) { + webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().get().click(); + } + } + + private void clickAboutLink() { + webDriver.findElement(By.partialLinkText("About")).click(); + } + + private void clickAboutUsLink() { + webDriver.findElement(By.partialLinkText("About Baeldung.")).click(); + } + + public boolean isAuthorInformationAvailable() { + return webDriver + .findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")) + .isDisplayed(); + } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java new file mode 100644 index 0000000000..f8d9a5dada --- /dev/null +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java @@ -0,0 +1,41 @@ +package test.java.com.baeldung.selenium.junit; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import main.java.com.baeldung.selenium.SeleniumExample; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SeleniumWithJUnitLiveTest { + + private static SeleniumExample seleniumExample; + private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; + + @BeforeClass + public static void setUp() { + seleniumExample = new SeleniumExample(); + } + + @AfterClass + public static void tearDown() { + seleniumExample.closeWindow(); + } + + @Test + public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { + try { + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); + } catch (Exception exception) { + exception.printStackTrace(); + seleniumExample.closeWindow(); + } + } + +} diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java deleted file mode 100644 index f183a613e7..0000000000 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java +++ /dev/null @@ -1,32 +0,0 @@ -package test.java.com.baeldung.selenium.junit; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import main.java.com.baeldung.selenium.SeleniumExample; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TestSeleniumWithJUnit { - - private SeleniumExample seleniumExample; - private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; - - @Before - public void setUp() { - seleniumExample = new SeleniumExample(); - } - - @After - public void tearDown() { - seleniumExample.closeWindow(); - } - - @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expectedTitle); - } -} diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java new file mode 100644 index 0000000000..5ec9ade39f --- /dev/null +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java @@ -0,0 +1,40 @@ +package test.java.com.baeldung.selenium.testng; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import main.java.com.baeldung.selenium.SeleniumExample; + +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +public class SeleniumWithTestNGLiveTest { + + private SeleniumExample seleniumExample; + private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung"; + + @BeforeSuite + public void setUp() { + seleniumExample = new SeleniumExample(); + } + + @AfterSuite + public void tearDown() { + seleniumExample.closeWindow(); + } + + @Test + public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() { + try { + seleniumExample.getAboutBaeldungPage(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); + assertEquals(actualTitle, expecteTilteAboutBaeldungPage); + assertTrue(seleniumExample.isAuthorInformationAvailable()); + } catch (Exception exception) { + exception.printStackTrace(); + seleniumExample.closeWindow(); + } + } +} diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java deleted file mode 100644 index 3c94f3d440..0000000000 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java +++ /dev/null @@ -1,32 +0,0 @@ -package test.java.com.baeldung.selenium.testng; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import main.java.com.baeldung.selenium.SeleniumExample; - -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; - -public class TestSeleniumWithTestNG { - - private SeleniumExample seleniumExample; - private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; - - @BeforeSuite - public void setUp() { - seleniumExample = new SeleniumExample(); - } - - @AfterSuite - public void tearDown() { - seleniumExample.closeWindow(); - } - - @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitle = seleniumExample.getTitle(); - assertNotNull(actualTitle); - assertEquals(actualTitle, expectedTitle); - } -} diff --git a/sockets/pom.xml b/sockets/pom.xml deleted file mode 100644 index 24e8e436f3..0000000000 --- a/sockets/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - 4.0.0 - com.baeldung - sockets - 1.0 - sockets - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - junit - junit - 4.3 - test - - - - diff --git a/spring-akka/README.md b/spring-akka/README.md new file mode 100644 index 0000000000..0f1c013214 --- /dev/null +++ b/spring-akka/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring with Akka](http://www.baeldung.com/akka-with-spring) diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml index 6299448ec8..eb33ca4848 100644 --- a/spring-akka/pom.xml +++ b/spring-akka/pom.xml @@ -65,9 +65,54 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + 4.3.2.RELEASE @@ -75,6 +120,8 @@ 4.12 3.5.1 + 2.19.1 + \ No newline at end of file diff --git a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java index 624e289812..aa5941c763 100644 --- a/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java +++ b/spring-akka/src/main/java/org/baeldung/akka/SpringExtension.java @@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId - 4.0.0 - com.baeldung - spring-all - 0.1-SNAPSHOT + + 4.0.0 + com.baeldung + spring-all + 0.1-SNAPSHOT - spring-all - war + spring-all + war - - org.springframework.boot - spring-boot-starter-parent - 1.3.6.RELEASE - + + org.springframework.boot + spring-boot-starter-parent + 1.3.6.RELEASE + - - - com.fasterxml.jackson.core - jackson-databind - + + + com.fasterxml.jackson.core + jackson-databind + - + - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework - spring-orm - - - org.springframework - spring-context - + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-orm + + + org.springframework + spring-context + - + - - org.springframework - spring-aspects - + + org.springframework + spring-aspects + - + - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.javassist - javassist - - - mysql - mysql-connector-java - runtime - - - org.hsqldb - hsqldb - - - + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.javassist + javassist + + + mysql + mysql-connector-java + runtime + + + org.hsqldb + hsqldb + - - org.hibernate - hibernate-validator - + - + + org.hibernate + hibernate-validator + - - javax.servlet - javax.servlet-api - provided - + - - javax.servlet - jstl - runtime - + + javax.servlet + javax.servlet-api + provided + - + + javax.servlet + jstl + runtime + - - com.google.guava - guava - ${guava.version} - - - + - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - - - - org.slf4j - jcl-over-slf4j - - - - org.slf4j - log4j-over-slf4j - + + com.google.guava + guava + ${guava.version} + - + - - org.springframework - spring-test - test - + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j + - - junit - junit - test - + - - org.assertj - assertj-core - 3.5.1 - test - + + org.springframework + spring-test + test + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + junit + junit + test + - - org.mockito - mockito-core - test - + + org.assertj + assertj-core + 3.5.1 + test + - - org.easymock - easymock - 3.4 - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - + + org.mockito + mockito-core + test + - + + org.easymock + easymock + 3.4 + test + + + org.ehcache + ehcache + 3.1.3 + - + - - org.springframework - spring-framework-bom - ${org.springframework.version} - pom - import - + - - org.springframework - spring-core - ${org.springframework.version} - + - + + org.springframework + spring-framework-bom + ${org.springframework.version} + pom + import + - + + org.springframework + spring-core + ${org.springframework.version} + - - spring-all - - - src/main/resources - true - - + - + - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - + + spring-all + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-war-plugin - - false - - + - - org.apache.maven.plugins - maven-surefire-plugin - - - - - - - - - + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.apache.maven.plugins + maven-war-plugin + + false + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + + + + + + - + - - - 4.3.1.RELEASE - 4.0.4.RELEASE - 3.20.0-GA - 1.2 + - - 4.3.11.Final - 5.1.38 + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + + 4.3.1.RELEASE + 4.0.4.RELEASE + 3.20.0-GA + 1.2 - - 1.7.13 - 1.1.3 + + 4.3.11.Final + 5.1.38 - - 5.2.2.Final + + 1.7.13 + 1.1.3 - - 19.0 - 3.4 + + 5.2.2.Final - - 1.3 - 4.12 - 1.10.19 + + 19.0 + 3.4 - 4.4.1 - 4.5 + + 1.3 + 4.12 + 1.10.19 - 2.9.0 + 4.4.1 + 4.5 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + 2.9.0 - + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java index 38b5a5a3ec..02b8c3c159 100644 --- a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java +++ b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java @@ -72,5 +72,5 @@ public abstract class AbstractService { public String getAddress5(final Customer customer) { return customer.getAddress(); } - + } diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index 443635fb70..ec6cf19785 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -11,21 +11,21 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class StudentControllerConfig implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(WebConfig.class); - root.setServletContext(sc); + @Override + public void onStartup(ServletContext sc) throws ServletException { + AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.register(WebConfig.class); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + root.setServletContext(sc); - DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); - ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/test/*"); - } + DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext()); + + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); + appServlet.setLoadOnStartup(1); + appServlet.addMapping("/test/*"); + } } diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java index f55af69c88..251a1affa1 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -11,13 +11,13 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" }) +@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } - + @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); diff --git a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java index 95903bcc40..4b38b4dd34 100644 --- a/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java +++ b/spring-all/src/main/java/org/baeldung/controller/controller/RestController.java @@ -7,15 +7,15 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; @Controller -public class RestController{ +public class RestController { - @GetMapping(value="/student/{studentId}") - public @ResponseBody Student getTestData(@PathVariable Integer studentId) { - Student student = new Student(); - student.setName("Peter"); - student.setId(studentId); + @GetMapping(value = "/student/{studentId}") + public @ResponseBody Student getTestData(@PathVariable Integer studentId) { + Student student = new Student(); + student.setName("Peter"); + student.setId(studentId); - return student; + return student; - } + } } diff --git a/spring-all/src/main/java/org/baeldung/controller/student/Student.java b/spring-all/src/main/java/org/baeldung/controller/student/Student.java index ee706d7028..5f49e5ceb9 100644 --- a/spring-all/src/main/java/org/baeldung/controller/student/Student.java +++ b/spring-all/src/main/java/org/baeldung/controller/student/Student.java @@ -1,33 +1,33 @@ package org.baeldung.controller.student; public class Student { - private String name; - - private int id; + private String name; - public String getName() { - return name; - } + private int id; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int getId() { - return id; - } + public void setName(String name) { + this.name = name; + } - public void setId(int id) { - this.id = id; - } - - @Override - public int hashCode(){ - return this.id; - } - - @Override - public boolean equals(Object obj){ - return this.name.equals(((Student)obj).getName()); - } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + return this.id; + } + + @Override + public boolean equals(Object obj) { + return this.name.equals(((Student) obj).getName()); + } } \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java new file mode 100755 index 0000000000..25957539df --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/calculator/SquaredCalculator.java @@ -0,0 +1,24 @@ +package org.baeldung.ehcache.calculator; + +import org.baeldung.ehcache.config.CacheHelper; + +public class SquaredCalculator { + private CacheHelper cache; + + public int getSquareValueOfNumber(int input) { + if (cache.getSquareNumberCache().containsKey(input)) { + return cache.getSquareNumberCache().get(input); + } + + System.out.println("Calculating square value of " + input + " and caching result."); + + int squaredValue = (int) Math.pow(input, 2); + cache.getSquareNumberCache().put(input, squaredValue); + + return squaredValue; + } + + public void setCache(CacheHelper cache) { + this.cache = cache; + } +} diff --git a/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java new file mode 100755 index 0000000000..7f59ad8cfb --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/ehcache/config/CacheHelper.java @@ -0,0 +1,29 @@ +package org.baeldung.ehcache.config; + +import org.ehcache.Cache; +import org.ehcache.CacheManager; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; + +public class CacheHelper { + + private CacheManager cacheManager; + private Cache squareNumberCache; + + public CacheHelper() { + cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(); + cacheManager.init(); + + squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10))); + } + + public Cache getSquareNumberCache() { + return squareNumberCache; + } + + public Cache getSquareNumberCacheFromCacheManager() { + return cacheManager.getCache("squaredNumber", Integer.class, Integer.class); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java index f96184a8a3..97d7fe0ffa 100644 --- a/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java @@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer { super(); } - @Bean public PropertyPlaceholderConfigurer propertyConfigurer() { final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer(); diff --git a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java index ae1c6157db..562069bc9a 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java +++ b/spring-all/src/main/java/org/baeldung/scopes/HelloMessageGenerator.java @@ -2,14 +2,14 @@ package org.baeldung.scopes; public class HelloMessageGenerator { - private String message; + private String message; - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(final String message) { - this.message = message; - } + public void setMessage(final String message) { + this.message = message; + } } diff --git a/spring-all/src/main/java/org/baeldung/scopes/Person.java b/spring-all/src/main/java/org/baeldung/scopes/Person.java index e6139c31dd..b070007a5c 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/Person.java +++ b/spring-all/src/main/java/org/baeldung/scopes/Person.java @@ -1,27 +1,27 @@ package org.baeldung.scopes; public class Person { - private String name; - private int age; + private String name; + private int age; - public Person() { - } + public Person() { + } - public Person(final String name, final int age) { - this.name = name; - } + public Person(final String name, final int age) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - @Override - public String toString() { - return "Person [name=" + name + "]"; - } + @Override + public String toString() { + return "Person [name=" + name + "]"; + } } diff --git a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java index bf733b75f9..1e3d5f3b14 100644 --- a/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java +++ b/spring-all/src/main/java/org/baeldung/scopes/ScopesController.java @@ -9,23 +9,23 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ScopesController { - public static final Logger LOG = Logger.getLogger(ScopesController.class); + public static final Logger LOG = Logger.getLogger(ScopesController.class); - @Resource(name = "requestMessage") - HelloMessageGenerator requestMessage; + @Resource(name = "requestMessage") + HelloMessageGenerator requestMessage; - @Resource(name = "sessionMessage") - HelloMessageGenerator sessionMessage; + @Resource(name = "sessionMessage") + HelloMessageGenerator sessionMessage; - @RequestMapping("/scopes") - public String getScopes(final Model model) { - LOG.info("Request Message:" + requestMessage.getMessage()); - LOG.info("Session Message" + sessionMessage.getMessage()); - requestMessage.setMessage("Good morning!"); - sessionMessage.setMessage("Good afternoon!"); - model.addAttribute("requestMessage", requestMessage.getMessage()); - model.addAttribute("sessionMessage", sessionMessage.getMessage()); - return "scopesExample"; - } + @RequestMapping("/scopes") + public String getScopes(final Model model) { + LOG.info("Request Message:" + requestMessage.getMessage()); + LOG.info("Session Message" + sessionMessage.getMessage()); + requestMessage.setMessage("Good morning!"); + sessionMessage.setMessage("Good afternoon!"); + model.addAttribute("requestMessage", requestMessage.getMessage()); + model.addAttribute("sessionMessage", sessionMessage.getMessage()); + return "scopesExample"; + } } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index 5a9b266388..a9bc298db3 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -16,42 +16,42 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver; @ComponentScan("org.baeldung.scopes") @EnableWebMvc public class ScopesConfig { - @Bean - public UrlBasedViewResolver setupViewResolver() { - final UrlBasedViewResolver resolver = new UrlBasedViewResolver(); - resolver.setPrefix("/WEB-INF/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } + @Bean + public UrlBasedViewResolver setupViewResolver() { + final UrlBasedViewResolver resolver = new UrlBasedViewResolver(); + resolver.setPrefix("/WEB-INF/view/"); + resolver.setSuffix(".jsp"); + resolver.setViewClass(JstlView.class); + return resolver; + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator requestMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator requestMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator sessionMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator sessionMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) - public HelloMessageGenerator globalSessionMessage() { - return new HelloMessageGenerator(); - } + @Bean + @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + public HelloMessageGenerator globalSessionMessage() { + return new HelloMessageGenerator(); + } - @Bean - @Scope("prototype") - public Person personPrototype() { - return new Person(); - } + @Bean + @Scope("prototype") + public Person personPrototype() { + return new Person(); + } - @Bean - @Scope("singleton") - public Person personSingleton() { - return new Person(); - } + @Bean + @Scope("singleton") + public Person personSingleton() { + return new Person(); + } } diff --git a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java index 4abd3cc813..ce34adf6c1 100644 --- a/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java +++ b/spring-all/src/main/java/org/baeldung/spring43/cache/Foo.java @@ -11,7 +11,6 @@ public class Foo { private static final AtomicInteger instanceCount = new AtomicInteger(0); - private final int instanceNum; public Foo() { diff --git a/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java rename to spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java index 2f41766cb6..0c010cf732 100644 --- a/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleTest.java +++ b/spring-all/src/test/java/org/baeldung/async/AsyncAnnotationExampleIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AsyncAnnotationExampleTest { +public class AsyncAnnotationExampleIntegrationTest { @Autowired private AsyncComponent asyncAnnotationExample; diff --git a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java rename to spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java index b91666261c..ffaa653a9a 100644 --- a/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLTest.java +++ b/spring-all/src/test/java/org/baeldung/async/AsyncWithXMLIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:springAsync-config.xml") -public class AsyncWithXMLTest { +public class AsyncWithXMLIntegrationTest { @Autowired private AsyncComponent asyncAnnotationExample; diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java similarity index 80% rename from spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java index 44f1767405..82c8704360 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -18,17 +18,16 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class ) -public class ControllerAnnotationTest { - - private MockMvc mockMvc; +@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) +public class ControllerAnnotationIntegrationTest { + + private MockMvc mockMvc; @Autowired private WebApplicationContext wac; - + private Student selectedStudent; @Before @@ -43,9 +42,7 @@ public class ControllerAnnotationTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")) - .andReturn() - .getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); @@ -57,9 +54,7 @@ public class ControllerAnnotationTest { @Test public void testRestController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); @@ -72,9 +67,7 @@ public class ControllerAnnotationTest { @Test public void testRestAnnotatedController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); diff --git a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java similarity index 85% rename from spring-all/src/test/java/org/baeldung/controller/ControllerTest.java rename to spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java index f5e41cd5a2..8e8a021530 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration({"classpath:test-mvc.xml"}) -public class ControllerTest { +@ContextConfiguration({ "classpath:test-mvc.xml" }) +public class ControllerIntegrationTest { private MockMvc mockMvc; @@ -41,9 +41,7 @@ public class ControllerTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")) - .andReturn() - .getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); @@ -55,9 +53,7 @@ public class ControllerTest { @Test public void testRestController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); @@ -70,9 +66,7 @@ public class ControllerTest { @Test public void testRestAnnotatedController() throws Exception { - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)) - .andReturn().getResponse() - .getContentAsString(); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString(); ObjectMapper reader = new ObjectMapper(); diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java index ec0d46876e..ae3d53fb9b 100644 --- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java @@ -14,7 +14,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessAnnotationTest { +public class DataAccessAnnotationIntegrationTest { @DataAccess(entity = Person.class) private GenericDAO personGenericDAO; diff --git a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java rename to spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java index e47d03c961..bab2574cd2 100644 --- a/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackTest.java +++ b/spring-all/src/test/java/org/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) -public class DataAccessFieldCallbackTest { +public class DataAccessFieldCallbackIntegrationTest { @Autowired private ConfigurableListableBeanFactory configurableListableBeanFactory; diff --git a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java new file mode 100644 index 0000000000..ab7aebf7a1 --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java @@ -0,0 +1,43 @@ +package org.baeldung.ehcache; + +import org.baeldung.ehcache.calculator.SquaredCalculator; +import org.baeldung.ehcache.config.CacheHelper; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class SquareCalculatorTest { + private SquaredCalculator squaredCalculator = new SquaredCalculator(); + private CacheHelper cacheHelper = new CacheHelper(); + + @Before + public void setup() { + squaredCalculator.setCache(cacheHelper); + } + + @Test + public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() { + for (int i = 10; i < 15; i++) { + assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } + + @Test + public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() { + for (int i = 10; i < 15; i++) { + assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + + for (int i = 10; i < 15; i++) { + assertTrue(cacheHelper.getSquareNumberCache().containsKey(i)); + System.out.println("Square value of " + i + " is: " + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + } + } +} diff --git a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java similarity index 99% rename from spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java rename to spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java index d544409254..4a92aa838f 100644 --- a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOTest.java +++ b/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class) -public class EmployeeDAOTest { +public class EmployeeDAOIntegrationTest { @Autowired private EmployeeDAO employeeDao; diff --git a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java index 2b65928da8..cf5ca132e6 100644 --- a/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/profiles/DevProfileWithAnnotationIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("dev") @ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DevProfileWithAnnotationTest { +public class DevProfileWithAnnotationIntegrationTest { @Autowired DatasourceConfig datasourceConfig; diff --git a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java similarity index 94% rename from spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java index 551636bd31..5bacaef07b 100644 --- a/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/profiles/ProductionProfileWithAnnotationIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("production") @ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ProductionProfileWithAnnotationTest { +public class ProductionProfileWithAnnotationIntegrationTest { @Autowired DatasourceConfig datasourceConfig; diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java index 92af3f52f0..e0eccc978a 100644 --- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertyPlaceHolderPropertiesIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig2.class), @ContextConfiguration(classes = ChildConfig2.class) }) -public class ParentChildPropertyPlaceHolderPropertiesTest { +public class ParentChildPropertyPlaceHolderPropertiesIntegrationTest { @Autowired private WebApplicationContext wac; diff --git a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java rename to spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java index 3ffd490c87..e9990523a7 100644 --- a/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/parentchild/ParentChildPropertySourcePropertiesIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class), @ContextConfiguration(classes = ChildConfig.class) }) -public class ParentChildPropertySourcePropertiesTest { +public class ParentChildPropertySourcePropertiesIntegrationTest { @Autowired private WebApplicationContext wac; diff --git a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java similarity index 90% rename from spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java rename to spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java index 9317c7bb7f..c5ca78aaa1 100644 --- a/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleTest.java +++ b/spring-all/src/test/java/org/baeldung/scheduling/ScheduledAnnotationExampleIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringSchedulingConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ScheduledAnnotationExampleTest { +public class ScheduledAnnotationExampleIntegrationTest { @Test public void testScheduledAnnotation() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java similarity index 89% rename from spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java rename to spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java index 0fca4d21c8..08df73f8fd 100644 --- a/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigTest.java +++ b/spring-all/src/test/java/org/baeldung/scheduling/SchedulingWithXmlConfigIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:springScheduled-config.xml") -public class SchedulingWithXmlConfigTest { +public class SchedulingWithXmlConfigIntegrationTest { @Test public void testXmlBasedScheduling() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java index b1dd248c26..59b9e225ad 100644 --- a/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java +++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesTest.java @@ -8,36 +8,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; public class ScopesTest { - private static final String NAME = "John Smith"; - private static final String NAME_OTHER = "Anna Jones"; + private static final String NAME = "John Smith"; + private static final String NAME_OTHER = "Anna Jones"; - @Test - public void testScopeSingleton() { - final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); + @Test + public void testScopeSingleton() { + final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); - final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); - final Person personSingletonB = (Person) applicationContext.getBean("personSingleton"); + final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); + final Person personSingletonB = (Person) applicationContext.getBean("personSingleton"); - personSingletonA.setName(NAME); - Assert.assertEquals(NAME, personSingletonB.getName()); + personSingletonA.setName(NAME); + Assert.assertEquals(NAME, personSingletonB.getName()); - ((AbstractApplicationContext) applicationContext).close(); - } + ((AbstractApplicationContext) applicationContext).close(); + } - @Test - public void testScopePrototype() { - final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); + @Test + public void testScopePrototype() { + final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); - final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); - final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype"); + final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); + final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype"); - personPrototypeA.setName(NAME); - personPrototypeB.setName(NAME_OTHER); + personPrototypeA.setName(NAME); + personPrototypeB.setName(NAME_OTHER); - Assert.assertEquals(NAME, personPrototypeA.getName()); - Assert.assertEquals(NAME_OTHER, personPrototypeB.getName()); + Assert.assertEquals(NAME, personPrototypeA.getName()); + Assert.assertEquals(NAME_OTHER, personPrototypeB.getName()); - ((AbstractApplicationContext) applicationContext).close(); - } + ((AbstractApplicationContext) applicationContext).close(); + } } diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java similarity index 75% rename from spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java rename to spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java index aa3acb113f..fff2716a64 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = AttributeAnnotationConfiguration.class) @WebAppConfiguration -public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests { +public class AttributeAnnotationIntegrationTest extends AbstractJUnit4SpringContextTests { private MockMvc mockMvc; @@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception { - String result = this.mockMvc.perform(get("/test") - .accept(MediaType.ALL)) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Assert.assertEquals("login = john, query = invoices", result); } diff --git a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java similarity index 92% rename from spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java rename to spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java index bfd6e5047c..986932dafe 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/cache/CacheRefinementsIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertEquals; @ContextConfiguration(classes = CacheRefinementsConfiguration.class) -public class CacheRefinementsTest extends AbstractJUnit4SpringContextTests { +public class CacheRefinementsIntegrationTest extends AbstractJUnit4SpringContextTests { private ExecutorService executorService = Executors.newFixedThreadPool(10); diff --git a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java similarity index 80% rename from spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java rename to spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java index 04fabbc834..d0af48cd0e 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/composedmapping/ComposedMappingIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = ComposedMappingConfiguration.class) @WebAppConfiguration -public class ComposedMappingTest extends AbstractJUnit4SpringContextTests { +public class ComposedMappingIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private AppointmentService appointmentService; @@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception { - this.mockMvc.perform(get("/appointments") - .accept(MediaType.ALL)) - .andExpect(status().isOk()); + this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk()); verify(appointmentService); } diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java similarity index 71% rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java index 82caae15fe..871a985479 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ConfigurationConstructorInjectionIntegrationTest.java @@ -7,8 +7,8 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; -@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class}) -public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests { +@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class }) +public class ConfigurationConstructorInjectionIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired public FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java similarity index 86% rename from spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java rename to spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java index be0cf77a62..83fa11294e 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/ctor/ImplicitConstructorIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration("classpath:implicit-ctor-context.xml") -public class ImplicitConstructorTest extends AbstractJUnit4SpringContextTests { +public class ImplicitConstructorIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java similarity index 87% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java index e29d89a679..956df44821 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/DefaultMethodsInjectionIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertEquals; @ContextConfiguration("classpath:defaultmethods-context.xml") -public class DefaultMethodsInjectionTest extends AbstractJUnit4SpringContextTests { +public class DefaultMethodsInjectionIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private IDateHolder dateHolder; diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java similarity index 76% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index 89c96ba1d4..b4ac7e8ccf 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(classes = TransactionalTestConfiguration.class) -public class TransactionalTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { +public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { @Test public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java index 946b19d00d..8a8cec3f86 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalTestConfiguration.java @@ -1,6 +1,5 @@ package org.baeldung.spring43.defaultmethods; - import javax.sql.DataSource; import org.springframework.context.annotation.Bean; diff --git a/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java similarity index 87% rename from spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java rename to spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java index eeeb005f81..6d06bfdc2a 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/depresolution/ObjectProviderIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = ObjectProviderConfiguration.class) -public class ObjectProviderTest extends AbstractJUnit4SpringContextTests { +public class ObjectProviderIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private FooService fooService; diff --git a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java similarity index 58% rename from spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java rename to spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java index b696760f68..69cce15029 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/scopeannotations/ScopeAnnotationsIntegrationTest.java @@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ContextConfiguration(classes = ScopeAnnotationsConfiguration.class) @WebAppConfiguration -public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { +public class ScopeAnnotationsIntegrationTest extends AbstractJUnit4SpringContextTests { private MockMvc mockMvc; @@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) - .build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception { MockHttpSession session = new MockHttpSession(); - String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request") - .session(session) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); - String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request") - .session(session) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2); } @@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { MockHttpSession session1 = new MockHttpSession(); MockHttpSession session2 = new MockHttpSession(); - String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session") - .session(session2) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2); @@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests { MockHttpSession session1 = new MockHttpSession(); MockHttpSession session2 = new MockHttpSession(); - String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application") - .session(session1) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); - String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application") - .session(session2) - .accept(MediaType.ALL)).andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2); diff --git a/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java rename to spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java index 2b45ae4e68..e12baed7e0 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/asynchronous/AsynchronousCustomSpringEventsIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AsynchronousCustomSpringEventsTest { +public class AsynchronousCustomSpringEventsIntegrationTest { @Autowired private CustomSpringEventPublisher publisher; diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java similarity index 92% rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java index d971698e3f..ac8758bbf6 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/ContextRefreshedListenerIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ContextRefreshedListenerTest { +public class ContextRefreshedListenerIntegrationTest { @Test public void testContextRefreshedListener() throws InterruptedException { diff --git a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java rename to spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java index b559ca9fc9..f9783f57dc 100644 --- a/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsTest.java +++ b/spring-all/src/test/java/org/baeldung/springevents/synchronous/SynchronousCustomSpringEventsIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SynchronousCustomSpringEventsTest { +public class SynchronousCustomSpringEventsIntegrationTest { @Autowired private CustomSpringEventPublisher publisher; diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java index 523a27c2c4..6263482948 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringStartupTest { +public class SpringStartupIntegrationTest { @Autowired private ApplicationContext ctx; diff --git a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java similarity index 93% rename from spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java rename to spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java index 19a35bb92b..a46d24fa3b 100644 --- a/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigTest.java +++ b/spring-all/src/test/java/org/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:startupConfig.xml") -public class SpringStartupXMLConfigTest { +public class SpringStartupXMLConfigIntegrationTest { @Autowired private ApplicationContext ctx; diff --git a/spring-autowire/README.md b/spring-autowire/README.md new file mode 100644 index 0000000000..d5b8221b25 --- /dev/null +++ b/spring-autowire/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) diff --git a/spring-autowire/pom.xml b/spring-autowire/pom.xml index e28efdae61..fd03c77605 100644 --- a/spring-autowire/pom.xml +++ b/spring-autowire/pom.xml @@ -57,7 +57,48 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java index 725a9b8406..18ff11a49c 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java @@ -3,9 +3,9 @@ package com.baeldung.autowire.sample; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { - public static void main(String[] args) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); - FooService fooService = ctx.getBean(FooService.class); - fooService.doStuff(); - } + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); + FooService fooService = ctx.getBean(FooService.class); + fooService.doStuff(); + } } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java index fb704453fc..e67a376d25 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java @@ -9,5 +9,5 @@ public class BarFormatter implements Formatter { public String format() { return "bar"; } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java index 73966e9e43..57f93a53d7 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java @@ -9,5 +9,5 @@ public class FooFormatter implements Formatter { public String format() { return "foo"; } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java index eccea4351a..c55d93da11 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java @@ -5,13 +5,13 @@ import org.springframework.stereotype.Component; @Component public class FooService { - + @Autowired @FormatterType("Foo") private Formatter formatter; - - public String doStuff(){ + + public String doStuff() { return formatter.format(); } - + } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java index 83716d6e92..59d718050a 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java @@ -2,6 +2,6 @@ package com.baeldung.autowire.sample; public interface Formatter { - String format(); + String format(); } diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java index 7ffc308c9a..f2961745b5 100644 --- a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java @@ -8,10 +8,10 @@ import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Qualifier; @Qualifier -@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER}) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface FormatterType { - + String value(); } diff --git a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java similarity index 74% rename from spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java rename to spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java index 4607f527d9..34ba7902ca 100644 --- a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java +++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java @@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class) -public class FooServiceTest { - +@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) +public class FooServiceIntegrationTest { + @Autowired FooService fooService; - + @Test - public void whenFooFormatterType_thenReturnFoo(){ + public void whenFooFormatterType_thenReturnFoo() { Assert.assertEquals("foo", fooService.doStuff()); } } diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 2a87b46021..1610d77e81 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -1,2 +1,7 @@ ###The Course The "REST With Spring" Classes: http://bit.ly/restwithspring + +###Relevant Articles: +- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 5a20ff5602..a2555259b0 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -88,12 +88,12 @@ org.webjars bootstrap - 3.3.4 + 3.3.7-1 org.webjars jquery - 2.1.4 + 3.1.1 @@ -133,10 +133,56 @@ 2.2.1 + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + spring-snapshots diff --git a/spring-boot/src/main/java/com/baeldung/TestController.java b/spring-boot/src/main/java/com/baeldung/TestController.java index 19a1c18c6b..0e28ca67f8 100644 --- a/spring-boot/src/main/java/com/baeldung/TestController.java +++ b/spring-boot/src/main/java/com/baeldung/TestController.java @@ -6,10 +6,10 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { - - @RequestMapping(value="/") - public String welcome(Model model){ - return "index"; - } + + @RequestMapping(value = "/") + public String welcome(Model model) { + return "index"; + } } diff --git a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java index c14dc682af..35490131c6 100644 --- a/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/WebjarsdemoApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebjarsdemoApplication { - public static void main(String[] args) { - SpringApplication.run(WebjarsdemoApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(WebjarsdemoApplication.class, args); + } } diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index 95abbf894c..cd696eae70 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; -@SpringBootApplication(scanBasePackages = { "com.baeldung.git"}) +@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); @@ -21,6 +21,3 @@ public class CommitIdApplication { return c; } } - - - diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java index 1da2bd2989..6d44e02ec2 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitInfoController.java @@ -22,7 +22,7 @@ public class CommitInfoController { @RequestMapping("/commitId") public Map getCommitId() { Map result = new HashMap<>(); - result.put("Commit message",commitMessage); + result.put("Commit message", commitMessage); result.put("Commit branch", branch); result.put("Commit id", commitId); return result; diff --git a/spring-boot/src/main/java/com/baeldung/git/README.md b/spring-boot/src/main/java/com/baeldung/git/README.md new file mode 100644 index 0000000000..7e6a597c28 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/git/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html index 046d21600a..2c4387ed10 100644 --- a/spring-boot/src/main/resources/templates/index.html +++ b/spring-boot/src/main/resources/templates/index.html @@ -1,19 +1,19 @@ WebJars Demo - +

- × + × Success! It is working as we expected.
- - + + - \ No newline at end of file + diff --git a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java similarity index 80% rename from spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java index 284cda5d31..3558682b97 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java @@ -9,10 +9,10 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = WebjarsdemoApplication.class) @WebAppConfiguration -public class WebjarsdemoApplicationTests { +public class WebjarsdemoApplicationIntegrationTest { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java similarity index 77% rename from spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java rename to spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java index e16791881e..348d594c05 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java @@ -12,9 +12,9 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @ContextConfiguration(classes = CommitIdApplication.class) -public class CommitIdTest { +public class CommitIdIntegrationTest { - private static final Logger LOG = LoggerFactory.getLogger(CommitIdTest.class); + private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class); @Value("${git.commit.message.short:UNKNOWN}") private String commitMessage; @@ -32,13 +32,10 @@ public class CommitIdTest { LOG.info(commitMessage); LOG.info(branch); - assertThat(commitMessage) - .isNotEqualTo("UNKNOWN"); + assertThat(commitMessage).isNotEqualTo("UNKNOWN"); - assertThat(branch) - .isNotEqualTo("UNKNOWN"); + assertThat(branch).isNotEqualTo("UNKNOWN"); - assertThat(commitId) - .isNotEqualTo("UNKNOWN"); + assertThat(commitId).isNotEqualTo("UNKNOWN"); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 80% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index ac7bcd62a9..3c5444942c 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -26,27 +26,20 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration -public class SpringBootApplicationTest { +public class SpringBootApplicationIntegrationTest { @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; - @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), - MediaType.APPLICATION_JSON.getSubtype(), - Charset.forName("utf8")); + MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")). - andExpect(MockMvcResultMatchers.status().isOk()). - andExpect(MockMvcResultMatchers.content().contentType(contentType)). - andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); } } diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 95% rename from spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java index 8a6b5139fe..233684bc24 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootJPATest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) -public class SpringBootJPATest { +public class SpringBootJPAIntegrationTest { @Autowired private GenericEntityRepository genericEntityRepository; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 98% rename from spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index d36a7906a3..cec25f20f9 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) -public class SpringBootMailTest { +public class SpringBootMailIntegrationTest { @Autowired private JavaMailSender javaMailSender; @@ -69,7 +69,6 @@ public class SpringBootMailTest { return wiserMessage.getMimeMessage().getSubject(); } - private SimpleMailMessage composeEmailMessage() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(userTo); diff --git a/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java similarity index 92% rename from spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java rename to spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java index 7911465048..57a8abc1ee 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/ApplicationTests.java +++ b/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @TestPropertySource("classpath:exception.properties") -public class ApplicationTests { +public class ApplicationIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 90% rename from spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java rename to spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java index 7f9b2ba912..4fcea35b4a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration -public class DemoApplicationTests { +public class DemoApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 84% rename from spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java index 9de7790a75..a844b26b2d 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -2,7 +2,7 @@ package org.baeldung.boot.repository; import static org.junit.Assert.assertThat; -import org.baeldung.boot.DemoApplicationTests; +import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import static org.hamcrest.Matchers.notNullValue; @@ -14,7 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class FooRepositoryTest extends DemoApplicationTests { +public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 88% rename from spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 4cb1b60cde..be992bcc36 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -4,7 +4,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; -import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.ApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.junit.Test; @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @Transactional @TestPropertySource("classpath:exception-hibernate.properties") -public class HibernateSessionTest extends ApplicationTests { +public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 81% rename from spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java rename to spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 5f5a49841a..55b7fa7216 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,6 +1,6 @@ package org.baeldung.boot.repository; -import org.baeldung.boot.ApplicationTests; +import org.baeldung.boot.ApplicationIntegrationTest; import org.baeldung.boot.model.Foo; import org.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; @@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class NoHibernateSessionTest extends ApplicationTests { +public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java similarity index 88% rename from spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java rename to spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java index c594610be2..5627855aa3 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat @RunWith(SpringRunner.class) @RestClientTest(DetailsServiceClient.class) -public class DetailsServiceClientTest { +public class DetailsServiceClientIntegrationTest { @Autowired private DetailsServiceClient client; @@ -30,8 +30,7 @@ public class DetailsServiceClientTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")) - .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-cloud-data-flow/README.MD b/spring-cloud-data-flow/README.MD index 8b13789179..17d0ec6286 100644 --- a/spring-cloud-data-flow/README.MD +++ b/spring-cloud-data-flow/README.MD @@ -1 +1,3 @@ - +### Relevant Articles: +- [Batch Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-batch-processing) +- [Getting Started with Stream Processing with Spring Cloud Data Flow](http://www.baeldung.com/spring-cloud-data-flow-stream-processing) diff --git a/spring-cloud-data-flow/data-flow-shell/spring-shell.log b/spring-cloud-data-flow/data-flow-shell/spring-shell.log new file mode 100644 index 0000000000..d497215e2a --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/spring-shell.log @@ -0,0 +1 @@ +// dataflow 1.2.0.RELEASE log opened at 2016-10-20 13:13:20 diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD index 8b13789179..c16ba3e247 100644 --- a/spring-cloud/spring-cloud-bootstrap/README.MD +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [Spring Cloud – Bootstrapping](http://www.baeldung.com/spring-cloud-bootstrapping) diff --git a/spring-cloud/spring-cloud-config/README.md b/spring-cloud/spring-cloud-config/README.md new file mode 100644 index 0000000000..b28c750ee6 --- /dev/null +++ b/spring-cloud/spring-cloud-config/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) diff --git a/spring-cloud/spring-cloud-eureka/README.md b/spring-cloud/spring-cloud-eureka/README.md new file mode 100644 index 0000000000..badf4c8d50 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) diff --git a/spring-cloud/spring-cloud-hystrix/README.MD b/spring-cloud/spring-cloud-hystrix/README.MD index 8b13789179..a235f6311f 100644 --- a/spring-cloud/spring-cloud-hystrix/README.MD +++ b/spring-cloud/spring-cloud-hystrix/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [A Guide to Spring Cloud Netflix – Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) diff --git a/dependency-injection/.gitignore b/spring-core/.gitignore similarity index 100% rename from dependency-injection/.gitignore rename to spring-core/.gitignore diff --git a/spring-core/README.md b/spring-core/README.md new file mode 100644 index 0000000000..5554412c31 --- /dev/null +++ b/spring-core/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire) diff --git a/dependency-injection/pom.xml b/spring-core/pom.xml similarity index 65% rename from dependency-injection/pom.xml rename to spring-core/pom.xml index 9e78a66ad6..9b94ba7b35 100644 --- a/dependency-injection/pom.xml +++ b/spring-core/pom.xml @@ -66,9 +66,10 @@ org.apache.maven.plugins maven-surefire-plugin - - **/*Test.java - + + **/*IntegrationTest.java + **/*LiveTest.java + @@ -85,6 +86,41 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 2.6 diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java index b736871f85..a78799f1d9 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredType.class) -public class FieldAutowiredTest { +public class FieldAutowiredIntegrationTest { @Autowired private ArbitraryDependency fieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java index cbdac68543..8f09e73c33 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredName.class) -public class FieldAutowiredNameTest { +public class FieldAutowiredNameIntegrationTest { @Autowired private ArbitraryDependency autowiredFieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java index cbc3d56f67..01317aef6f 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredQualifier.class) -public class FieldQualifierAutowiredTest { +public class FieldQualifierAutowiredIntegrationTest { @Autowired @Qualifier("autowiredFieldDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java index 665c9f1ddc..f5897febab 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectName.class) -public class FieldByNameInjectTest { +public class FieldByNameInjectIntegrationTest { @Inject @Named("yetAnotherFieldInjectDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java index 7561c39e76..45b7c8015c 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectType.class) -public class FieldInjectTest { +public class FieldInjectIntegrationTest { @Inject private ArbitraryDependency fieldInjectDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java index 7e5f7e7453..0fd6a0e4c1 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectQualifier.class) -public class FieldQualifierInjectTest { +public class FieldQualifierInjectIntegrationTest { @Inject @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java similarity index 94% rename from dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java index ef7e7b0aeb..63a25cb499 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class FieldResourceInjectionTest { +public class FieldResourceInjectionIntegrationTest { @Resource(name = "namedFile") private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java index 95e9fc0bd5..f5bb9f10cf 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class MethodByQualifierResourceTest { +public class MethodByQualifierResourceIntegrationTest { private File arbDependency; private File anotherArbDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java index ad9a9a4fb6..171cbfea47 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodByTypeResourceTest { +public class MethodByTypeResourceIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java index 1622d8896c..2e1c3c39a9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodResourceInjectionTest { +public class MethodResourceInjectionIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java index da104ecaae..d52660e9b8 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class NamedResourceTest { +public class NamedResourceIntegrationTest { @Resource(name = "namedFile") private File testFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java index 024c8e2bbe..3f812350c9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class QualifierResourceInjectionTest { +public class QualifierResourceInjectionIntegrationTest { @Resource @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java index aa7cfda975..ae13b2336a 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class SetterResourceInjectionTest { +public class SetterResourceInjectionIntegrationTest { private File defaultFile; diff --git a/spring-cucumber/README.md b/spring-cucumber/README.md new file mode 100644 index 0000000000..1e506f3a09 --- /dev/null +++ b/spring-cucumber/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Cucumber Spring Integration](http://www.baeldung.com/cucumber-spring-integration) diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index f3b9c983f0..b493962a75 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -73,17 +73,63 @@ - - - + + + org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index 60548dd6e3..820e7e8004 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -18,9 +18,9 @@ public class SpringDemoApplication extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringDemoApplication.class); } - + @Bean - public RestTemplate getRestTemplate(){ - return new RestTemplate(); + public RestTemplate getRestTemplate() { + return new RestTemplate(); } } diff --git a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java similarity index 84% rename from spring-cucumber/src/test/java/com/baeldung/CucumberTest.java rename to spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java index c31a35b271..56eb810c09 100644 --- a/spring-cucumber/src/test/java/com/baeldung/CucumberTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/CucumberIntegrationTest.java @@ -6,5 +6,5 @@ import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources") -public class CucumberTest { +public class CucumberIntegrationTest { } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java b/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java similarity index 85% rename from spring-cucumber/src/test/java/com/baeldung/OtherDefs.java rename to spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java index edbc14f319..17f298c3fb 100644 --- a/spring-cucumber/src/test/java/com/baeldung/OtherDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; -public class OtherDefs extends SpringIntegrationTest { +public class OtherDefsIntegrationTest extends SpringIntegrationTest { @When("^the client calls /baeldung$") public void the_client_issues_POST_hello() throws Throwable { executePost("http://localhost:8080/baeldung"); diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java similarity index 93% rename from spring-cucumber/src/test/java/com/baeldung/StepDefs.java rename to spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java index 865a1e13fa..8220d5e861 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefs.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java @@ -9,7 +9,7 @@ import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; -public class StepDefs extends SpringIntegrationTest { +public class StepDefsIntegrationTest extends SpringIntegrationTest { @When("^the client calls /version$") public void the_client_issues_GET_version() throws Throwable { diff --git a/spring-data-cassandra/pom.xml b/spring-data-cassandra/pom.xml index e5f8779942..5c1a42b8bd 100644 --- a/spring-data-cassandra/pom.xml +++ b/spring-data-cassandra/pom.xml @@ -23,6 +23,7 @@ 2.1.9.2 2.1.9.2 2.0-0 + 2.19.1 @@ -108,6 +109,52 @@ 1.7 - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-data-couchbase-2/pom.xml b/spring-data-couchbase-2/pom.xml index d24ef4aeaa..6716f82246 100644 --- a/spring-data-couchbase-2/pom.xml +++ b/spring-data-couchbase-2/pom.xml @@ -86,6 +86,17 @@ 1.7 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + @@ -99,7 +110,7 @@ 1.1.3 1.7.12 4.11 - + 2.19.1 diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java index 201b14cf0b..c357ab8596 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java @@ -19,22 +19,27 @@ public class Campus { @Field @NotNull private Point location; - + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Point getLocation() { return location; } + public void setLocation(Point location) { this.location = location; } @@ -42,13 +47,13 @@ public class Campus { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(name != null) { + if (name != null) { hash = hash * 31 + name.hashCode(); } - if(location != null) { + if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; @@ -56,30 +61,33 @@ public class Campus { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } - + @SuppressWarnings("unused") - private Campus() {} - + private Campus() { + } + public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } - + public static class Builder { private String id; private String name; private Point location; - + public static Builder newInstance() { return new Builder(); } - + public Campus build() { return new Campus(this); } @@ -93,7 +101,7 @@ public class Campus { this.name = name; return this; } - + public Builder location(Point location) { this.location = location; return this; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java index 9220e157ed..fd41427d20 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java @@ -24,7 +24,7 @@ public class Person { private DateTime created; @Field private DateTime updated; - + public Person(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; @@ -34,44 +34,53 @@ public class Person { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } - + @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } return hash; @@ -79,8 +88,10 @@ public class Person { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Person other = (Person) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java index 9c266c2c62..726ed2347e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java @@ -20,13 +20,13 @@ public class Student { private String id; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String firstName; @Field @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) + @Size(min = 1, max = 20) + @Pattern(regexp = NAME_REGEX) private String lastName; @Field @Past @@ -38,8 +38,9 @@ public class Student { private DateTime updated; @Version private long version; - - public Student() {} + + public Student() { + } public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { this.id = id; @@ -51,36 +52,47 @@ public class Student { public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public DateTime getDateOfBirth() { return dateOfBirth; } + public void setDateOfBirth(DateTime dateOfBirth) { this.dateOfBirth = dateOfBirth; } + public DateTime getCreated() { return created; } + public void setCreated(DateTime created) { this.created = created; } + public DateTime getUpdated() { return updated; } + public void setUpdated(DateTime updated) { this.updated = updated; } @@ -88,16 +100,16 @@ public class Student { @Override public int hashCode() { int hash = 1; - if(id != null) { + if (id != null) { hash = hash * 31 + id.hashCode(); } - if(firstName != null) { + if (firstName != null) { hash = hash * 31 + firstName.hashCode(); } - if(lastName != null) { + if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } - if(dateOfBirth != null) { + if (dateOfBirth != null) { hash = hash * 31 + dateOfBirth.hashCode(); } return hash; @@ -105,8 +117,10 @@ public class Student { @Override public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; + if ((obj == null) || (obj.getClass() != this.getClass())) + return false; + if (obj == this) + return true; Student other = (Student) obj; return this.hashCode() == other.hashCode(); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java index 66b672a4fd..751895502c 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java @@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository { private CouchbaseTemplate template; public List findByFirstNameStartsWith(String s) { - return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName") - .startKey(s) - .stale(Stale.FALSE), - Student.class); + return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class); } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java index 14b77759e3..717feb858f 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java index 331ddc553d..9bbdeec642 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository, CustomStudentRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java index 90cc36780a..49548bdbfb 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("PersonRepositoryService") public class PersonRepositoryService implements PersonService { - + private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java index 45e9b90a19..8398847f65 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("PersonTemplateService") public class PersonTemplateService implements PersonService { - + private static final String DESIGN_DOC = "person"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Person findOne(String id) { - return template.findById(id, Person.class); + public Person findOne(String id) { + return template.findById(id, Person.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java index 58304afc1c..65f5a6e78e 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java @@ -14,8 +14,9 @@ import org.springframework.stereotype.Service; @Service @Qualifier("StudentRepositoryService") public class StudentRepositoryService implements StudentService { - + private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java index c3808e0015..8d1292b5e4 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java @@ -14,17 +14,18 @@ import com.couchbase.client.java.view.ViewQuery; @Service @Qualifier("StudentTemplateService") public class StudentTemplateService implements StudentService { - + private static final String DESIGN_DOC = "student"; private CouchbaseTemplate template; + @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } - public Student findOne(String id) { - return template.findById(id, Student.class); + public Student findOne(String id) { + return template.findById(id, Student.class); } public List findAll() { diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index 2cf388f518..b1857222c5 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository; public interface CampusRepository extends CrudRepository { - @View(designDocument="campus", viewName="byName") + @View(designDocument = "campus", viewName = "byName") Set findByName(String name); - @Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation") + @Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation") Set findByLocationNear(Point point, Distance distance); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java index e441bec6e4..ef37106c6d 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface PersonRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java index 2a960d37de..0d790d2f39 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository { List findByFirstName(String firstName); + List findByLastName(String lastName); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java index d098c39011..58f00dda25 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -7,14 +7,14 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; public interface CampusService { - + Campus find(String id); Set findByName(String name); Set findByLocationNear(Point point, Distance distance); - + Set findAll(); - + void save(Campus campus); } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index 612774fec9..586f5f0dc1 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -15,21 +15,22 @@ import org.springframework.stereotype.Service; public class CampusServiceImpl implements CampusService { private CampusRepository repo; + @Autowired public void setCampusRepository(CampusRepository repo) { this.repo = repo; } - + @Override public Campus find(String id) { return repo.findOne(id); } - + @Override public Set findByName(String name) { return repo.findByName(name); } - + @Override public Set findByLocationNear(Point point, Distance distance) { return repo.findByLocationNear(point, distance); @@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService { public Set findAll() { Set campuses = new HashSet<>(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { campuses.add(it.next()); } return campuses; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index f1ff513bff..fe0a9e48cd 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class PersonServiceImpl implements PersonService { private PersonRepository repo; + @Autowired public void setPersonRepository(PersonRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class PersonServiceImpl implements PersonService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 65400636cf..248d824081 100644 --- a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.stereotype.Service; public class StudentServiceImpl implements StudentService { private StudentRepository repo; + @Autowired public void setStudentRepository(StudentRepository repo) { this.repo = repo; @@ -26,7 +27,7 @@ public class StudentServiceImpl implements StudentService { public List findAll() { List people = new ArrayList(); Iterator it = repo.findAll().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { people.add(it.next()); } return people; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java index 8e6b971dbf..a37e918101 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java @@ -12,9 +12,9 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" }) public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String BUCKET_NAME = "baeldung"; public static final String BUCKET_PASSWORD = ""; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java similarity index 78% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java index ce5cf7667d..d710e57def 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class PersonRepositoryServiceTest extends PersonServiceTest { +public class PersonRepositoryServiceIntegrationTest extends PersonServiceIntegrationTest { @Autowired @Qualifier("PersonRepositoryService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java index c3bf9f2138..4044183849 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java @@ -20,7 +20,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public abstract class PersonServiceTest extends IntegrationTest { +public abstract class PersonServiceIntegrationTest extends IntegrationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java similarity index 79% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java index 0238fa21fb..e19df8fc84 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class PersonTemplateServiceTest extends PersonServiceTest { +public class PersonTemplateServiceIntegrationTest extends PersonServiceIntegrationTest { @Autowired @Qualifier("PersonTemplateService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java similarity index 78% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java index 040453fd73..3b3f2a531a 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class StudentRepositoryServiceTest extends StudentServiceTest { +public class StudentRepositoryServiceIntegrationTest extends StudentServiceIntegrationTest { @Autowired @Qualifier("StudentRepositoryService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java similarity index 84% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java index 79948cbedf..fba549a9e5 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java @@ -22,7 +22,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public abstract class StudentServiceTest extends IntegrationTest { +public abstract class StudentServiceIntegrationTest extends IntegrationTest { static final String typeField = "_class"; static final String joe = "Joe"; @@ -30,27 +30,17 @@ public abstract class StudentServiceTest extends IntegrationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + StudentService studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); @@ -60,7 +50,7 @@ public abstract class StudentServiceTest extends IntegrationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -130,11 +120,11 @@ public abstract class StudentServiceTest extends IntegrationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java similarity index 79% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java index dd5be8e059..29fd605bc6 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.spring.data.couchbase.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -public class StudentTemplateServiceTest extends StudentServiceTest { +public class StudentTemplateServiceIntegrationTest extends StudentServiceIntegrationTest { @Autowired @Qualifier("StudentTemplateService") diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index f419ba3499..fe32305feb 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -38,29 +38,25 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { protected String getBucketPassword() { return DEFAULT_BUCKET_PASSWORD; } - + @Bean public Bucket campusBucket() throws Exception { return couchbaseCluster().openBucket("baeldung2", ""); } - + @Bean(name = "campusTemplate") public CouchbaseTemplate campusTemplate() throws Exception { - CouchbaseTemplate template = new CouchbaseTemplate( - couchbaseClusterInfo(), - campusBucket(), - mappingCouchbaseConverter(), - translationService()); + CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService()); template.setDefaultConsistency(getDefaultConsistency()); return template; } - + @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { baseMapping.mapEntity(Campus.class, campusTemplate()); } catch (Exception e) { - //custom Exception handling + // custom Exception handling } } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java similarity index 68% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java index 7e24952e32..71648cf59b 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java @@ -18,62 +18,30 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusServiceImplTest extends MultiBucketIntegationTest { - +public class CampusServiceImplIntegrationTest extends MultiBucketIntegationTest { + @Autowired private CampusServiceImpl campusService; - + @Autowired private CampusRepository campusRepo; - - private final Campus Brown = Campus.Builder.newInstance() - .id("campus:Brown") - .name("Brown") - .location(new Point(71.4025, 51.8268)) - .build(); - private final Campus Cornell = Campus.Builder.newInstance() - .id("campus:Cornell") - .name("Cornell") - .location(new Point(76.4833, 42.4459)) - .build(); - - private final Campus Columbia = Campus.Builder.newInstance() - .id("campus:Columbia") - .name("Columbia") - .location(new Point(73.9626, 40.8075)) - .build(); - - private final Campus Dartmouth = Campus.Builder.newInstance() - .id("campus:Dartmouth") - .name("Dartmouth") - .location(new Point(72.2887, 43.7044)) - .build(); + private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build(); - private final Campus Harvard = Campus.Builder.newInstance() - .id("campus:Harvard") - .name("Harvard") - .location(new Point(71.1167, 42.3770)) - .build(); + private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build(); - private final Campus Penn = Campus.Builder.newInstance() - .id("campus:Penn") - .name("Penn") - .location(new Point(75.1932, 39.9522)) - .build(); + private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build(); + + private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build(); + + private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build(); + + private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build(); + + private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build(); + + private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build(); - private final Campus Princeton = Campus.Builder.newInstance() - .id("campus:Princeton") - .name("Princeton") - .location(new Point(74.6514, 40.3340)) - .build(); - - private final Campus Yale = Campus.Builder.newInstance() - .id("campus:Yale") - .name("Yale") - .location(new Point(72.9223, 41.3163)) - .build(); - private final Point Boston = new Point(71.0589, 42.3601); private final Point NewYorkCity = new Point(74.0059, 40.7128); @@ -88,7 +56,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { campusRepo.save(Princeton); campusRepo.save(Yale); } - + @Test public final void givenNameHarvard_whenFindByName_thenReturnsHarvard() throws Exception { Set campuses = campusService.findByName(Harvard.getName()); @@ -97,14 +65,14 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.size() == 1); assertTrue(campuses.contains(Harvard)); } - + @Test public final void givenHarvardId_whenFind_thenReturnsHarvard() throws Exception { Campus actual = campusService.find(Harvard.getId()); assertNotNull(actual); assertEquals(Harvard, actual); } - + @Test public final void whenFindAll_thenReturnsAll() throws Exception { Set campuses = campusService.findAll(); @@ -125,7 +93,7 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest { assertTrue(campuses.contains(Harvard)); assertFalse(campuses.contains(Columbia)); } - + @Test public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception { Set campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL)); diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java similarity index 98% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java index e1a880d9da..819798d536 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java @@ -21,7 +21,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonServiceImplTest extends MultiBucketIntegationTest { +public class PersonServiceImplIntegrationTest extends MultiBucketIntegationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java similarity index 85% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java index 220c2c3b00..f37f11744d 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java @@ -23,7 +23,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentServiceImplTest extends MultiBucketIntegationTest { +public class StudentServiceImplIntegrationTest extends MultiBucketIntegationTest { static final String typeField = "_class"; static final String joe = "Joe"; @@ -31,28 +31,18 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { static final String joeCollegeId = "student:" + joe + ":" + college; static final DateTime joeCollegeDob = DateTime.now().minusYears(21); static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - static final JsonObject jsonJoeCollege = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", joe) - .put("lastName", college) - .put("created", DateTime.now().getMillis()) - .put("version", 1); + static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1); static final String judy = "Judy"; static final String jetson = "Jetson"; static final String judyJetsonId = "student:" + judy + ":" + jetson; static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - static final JsonObject jsonJudyJetson = JsonObject.empty() - .put(typeField, Student.class.getName()) - .put("firstName", judy) - .put("lastName", jetson) - .put("created", DateTime.now().getMillis()) - .put("version", 1); - + static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1); + @Autowired StudentServiceImpl studentService; - + @BeforeClass public static void setupBeforeClass() { Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); @@ -62,7 +52,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -77,7 +67,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertEquals(expectedStudent.getId(), actualStudent.getId()); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() { String firstName = "Er+ic"; String lastName = "Stratton"; @@ -87,7 +77,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { studentService.create(student); } - @Test(expected=ConstraintViolationException.class) + @Test(expected = ConstraintViolationException.class) public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() { String firstName = "Jane"; String lastName = "Doe"; @@ -132,11 +122,11 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; - for(Student p : resultList) { - if(p.getId().equals(student.getId())) { + for (Student p : resultList) { + if (p.getId().equals(student.getId())) { found = true; break; } @@ -146,8 +136,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Student p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (Student p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -157,8 +147,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Student p : resultList) { - if(p.getLastName().equals(lastName)) { + for (Student p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-elasticsearch/README.md b/spring-data-elasticsearch/README.md index 74d9e4f642..a7b090818e 100644 --- a/spring-data-elasticsearch/README.md +++ b/spring-data-elasticsearch/README.md @@ -1,6 +1,10 @@ ## Spring Data Elasticsearch - [Introduction to Spring Data Elasticsearch](http://www.baeldung.com/spring-data-elasticsearch-tutorial) +###Relevant Articles: +- [Elasticsearch Queries with Spring Data](http://www.baeldung.com/spring-data-elasticsearch-queries) +- [Guide to Elasticsearch in Java](http://www.baeldung.com/elasticsearch-java) + ### Build the Project with Tests Running ``` mvn clean install diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 084695c2f3..dcb702ab16 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -11,14 +11,16 @@ UTF-8 + 1.8 + 1.8 - 1.3.2.RELEASE 4.2.5.RELEASE 4.11 1.7.12 1.1.3 2.0.1.RELEASE + 2.19.1 @@ -27,6 +29,12 @@ spring-core ${org.springframework.version}
+ + org.springframework.data + spring-data-elasticsearch + ${elasticsearch.version} + + junit junit-dep @@ -39,16 +47,13 @@ ${org.springframework.version} test - - org.springframework.data - spring-data-elasticsearch - ${elasticsearch.version} - - net.java.dev.jna + + net.java.dev.jna jna 4.1.0 test + org.slf4j slf4j-api @@ -81,16 +86,55 @@ 1.2.13 + - - - maven-compiler-plugin - 2.3.2 - - 1.8 - 1.8 - - - - - + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + \ No newline at end of file diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index f93999a1cc..37e9fd46eb 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -32,18 +32,22 @@ public class Config { public Client client() { try { final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); - + logger.debug(tmpDir.toAbsolutePath().toString()); + // @formatter:off final Settings.Builder elasticsearchSettings = Settings.settingsBuilder().put("http.enabled", "false") .put("path.data", tmpDir.toAbsolutePath().toString()) .put("path.home", elasticsearchHome); + + return new NodeBuilder() + .local(true) + .settings(elasticsearchSettings) + .node() + .client(); + // @formatter:on - - logger.debug(tmpDir.toAbsolutePath().toString()); - - return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client(); } catch (final IOException ioex) { logger.error("Cannot create temp dir", ioex); throw new RuntimeException(); diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 0ea922bdd3..2a31b52602 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -10,10 +10,10 @@ import org.springframework.stereotype.Service; @Service public class ArticleServiceImpl implements ArticleService { - private ArticleRepository articleRepository; - + private final ArticleRepository articleRepository; + @Autowired - public void setArticleRepository(ArticleRepository articleRepository) { + public ArticleServiceImpl(ArticleRepository articleRepository) { this.articleRepository = articleRepository; } diff --git a/spring-data-elasticsearch/src/main/resources/logback.xml b/spring-data-elasticsearch/src/main/resources/logback.xml index 37a9e2edbf..db75fcbe40 100644 --- a/spring-data-elasticsearch/src/main/resources/logback.xml +++ b/spring-data-elasticsearch/src/main/resources/logback.xml @@ -8,10 +8,10 @@ - - - + + + diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java index db304ee78d..4ab5d40788 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/elasticsearch/ElasticSearchUnitTests.java @@ -43,8 +43,7 @@ public class ElasticSearchUnitTests { @Test public void givenJsonString_whenJavaObject_thenIndexDocument() { String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String index = response.getIndex(); String type = response.getType(); assertTrue(response.isCreated()); @@ -55,8 +54,7 @@ public class ElasticSearchUnitTests { @Test public void givenDocumentId_whenJavaObject_thenDeleteDocument() { String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(jsonObject).get(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get(); String id = response.getId(); DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get(); assertTrue(deleteResponse.isFound()); @@ -77,29 +75,11 @@ public class ElasticSearchUnitTests { @Test public void givenSearchParamters_thenReturnResults() { boolean isExecutedSuccessfully = true; - SearchResponse response = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response2 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response2 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); - SearchResponse response3 = client.prepareSearch() - .setTypes() - .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) - .setPostFilter(QueryBuilders.matchQuery("John", "Name*")) - .setFrom(0).setSize(60).setExplain(true) - .execute() - .actionGet(); + SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet(); try { response2.getHits(); response3.getHits(); @@ -114,14 +94,8 @@ public class ElasticSearchUnitTests { @Test public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { - XContentBuilder builder = XContentFactory.jsonBuilder() - .startObject() - .field("fullName", "Test") - .field("salary", "11500") - .field("age", "10") - .endObject(); - IndexResponse response = client.prepareIndex("people", "Doe") - .setSource(builder).get(); + XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject(); + IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get(); assertTrue(response.isCreated()); } } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java similarity index 96% rename from spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java rename to spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java index e10b5f48d7..1280c8e1de 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchIntegrationTest.java @@ -21,7 +21,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.spring.data.es.config.Config; import com.baeldung.spring.data.es.model.Article; @@ -29,8 +28,8 @@ import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) -public class ElasticSearchTest { +@ContextConfiguration(classes = Config.class) +public class ElasticSearchIntegrationTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java similarity index 97% rename from spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java rename to spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java index 1551d6442e..cc4bce0c75 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryIntegrationTest.java @@ -34,7 +34,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.spring.data.es.config.Config; import com.baeldung.spring.data.es.model.Article; @@ -42,8 +41,8 @@ import com.baeldung.spring.data.es.model.Author; import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) -public class ElasticSearchQueryTest { +@ContextConfiguration(classes = Config.class) +public class ElasticSearchQueryIntegrationTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 102344a3fa..fd212548d0 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -112,9 +112,55 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + UTF-8 @@ -130,6 +176,7 @@ 1.7.12 1.1.3 + 2.19.1 diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java index 06ad21647b..bb4b268ca7 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSIntegrationTest.java @@ -140,7 +140,7 @@ public class GridFSIntegrationTest { assertNotNull(gridFSDBFiles); assertThat(gridFSDBFiles.size(), is(2)); } - + @Test public void givenMetadataAndFilesExist_whenFindingAllFilesOnQuery_thenFilesWithMetadataAreFoundOnQuery() { DBObject metaDataUser1 = new BasicDBObject(); diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index b0cf62ef2e..653dd6b2f6 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -13,6 +13,7 @@ UTF-8 3.0.1 4.1.1.RELEASE + 2.19.1 @@ -83,12 +84,57 @@ - - - - maven-compiler-plugin - - - + + + + maven-compiler-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java index ac9a7260be..fb4fda1497 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java @@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; - -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver") - .setURI(URL); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java index 2b6394184d..81935b2293 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java @@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.server.Neo4jServer; import org.springframework.transaction.annotation.EnableTransactionManagement; - @EnableTransactionManagement -@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" }) @Configuration @EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory") -@Profile({"embedded", "test"}) +@Profile({ "embedded", "test" }) public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration { @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration(); - config - .driverConfiguration() - .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); + config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver"); return config; } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java index e48dfaf276..029754c0fc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java @@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.Collection; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Movie { @@ -21,9 +21,11 @@ public class Movie { private int released; private String tagline; - @Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List roles; + @Relationship(type = "ACTED_IN", direction = Relationship.INCOMING) + private List roles; - public Movie() { } + public Movie() { + } public String getTitle() { return title; @@ -56,6 +58,5 @@ public class Movie { public void setRoles(List roles) { this.roles = roles; } - - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java index d96dc07530..dc5a850f29 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.GraphId; @@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship; import java.util.List; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @NodeEntity public class Person { @GraphId @@ -21,7 +20,8 @@ public class Person { @Relationship(type = "ACTED_IN") private List movies; - public Person() { } + public Person() { + } public String getName() { return name; @@ -46,5 +46,5 @@ public class Person { public void setMovies(List movies) { this.movies = movies; } - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java index 20512a10ad..40dabb054b 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.neo4j.domain; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.voodoodyne.jackson.jsog.JSOGGenerator; import org.neo4j.ogm.annotation.EndNode; @@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode; import java.util.Collection; -@JsonIdentityInfo(generator=JSOGGenerator.class) +@JsonIdentityInfo(generator = JSOGGenerator.class) @RelationshipEntity(type = "ACTED_IN") public class Role { @GraphId diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java index 850d2336ba..1bd605a7bc 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java @@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository { Collection findByTitleContaining(@Param("title") String title); @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}") - List> graph(@Param("limit") int limit); + List> graph(@Param("limit") int limit); } - - diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java index 4c287f99a4..f7f694c07f 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -4,8 +4,7 @@ import com.baeldung.spring.data.neo4j.domain.Person; import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.stereotype.Repository; - @Repository public interface PersonRepository extends GraphRepository { - + } diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java index 532cc79091..d760d19066 100644 --- a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -15,31 +15,31 @@ public class MovieService { MovieRepository movieRepository; private Map toD3Format(Iterator> result) { - List> nodes = new ArrayList>(); - List> rels= new ArrayList>(); - int i=0; + List> nodes = new ArrayList>(); + List> rels = new ArrayList>(); + int i = 0; while (result.hasNext()) { Map row = result.next(); - nodes.add(map("title",row.get("movie"),"label","movie")); - int target=i; + nodes.add(map("title", row.get("movie"), "label", "movie")); + int target = i; i++; for (Object name : (Collection) row.get("cast")) { - Map actor = map("title", name,"label","actor"); + Map actor = map("title", name, "label", "actor"); int source = nodes.indexOf(actor); if (source == -1) { nodes.add(actor); source = i++; } - rels.add(map("source",source,"target",target)); + rels.add(map("source", source, "target", target)); } } return map("nodes", nodes, "links", rels); } private Map map(String key1, Object value1, String key2, Object value2) { - Map result = new HashMap(2); - result.put(key1,value1); - result.put(key2,value2); + Map result = new HashMap(2); + result.put(key1, value1); + result.put(key2, value2); return result; } diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java similarity index 91% rename from spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java rename to spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java index 8061b3c2a7..95bc38aafc 100644 --- a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) @ActiveProfiles(profiles = "test") -public class MovieRepositoryTest { +public class MovieRepositoryIntegrationTest { @Autowired private MovieRepository movieRepository; @@ -32,7 +32,7 @@ public class MovieRepositoryTest { @Autowired private PersonRepository personRepository; - public MovieRepositoryTest() { + public MovieRepositoryIntegrationTest() { } @Before @@ -82,8 +82,7 @@ public class MovieRepositoryTest { @DirtiesContext public void testFindAll() { System.out.println("findAll"); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertNotNull(result); assertEquals(1, result.size()); } @@ -93,8 +92,7 @@ public class MovieRepositoryTest { public void testFindByTitleContaining() { System.out.println("findByTitleContaining"); String title = "Italian"; - Collection result = - movieRepository.findByTitleContaining(title); + Collection result = movieRepository.findByTitleContaining(title); assertNotNull(result); assertEquals(1, result.size()); } @@ -126,8 +124,7 @@ public class MovieRepositoryTest { public void testDeleteAll() { System.out.println("deleteAll"); movieRepository.deleteAll(); - Collection result = - (Collection) movieRepository.findAll(); + Collection result = (Collection) movieRepository.findAll(); assertEquals(0, result.size()); } } diff --git a/spring-data-redis/README.md b/spring-data-redis/README.md index 89eae99f05..da44920e16 100644 --- a/spring-data-redis/README.md +++ b/spring-data-redis/README.md @@ -2,6 +2,7 @@ ### Relevant Articles: - [Introduction to Spring Data Redis](http://www.baeldung.com/spring-data-redis-tutorial) +- [PubSub Messaging with Spring Data Redis](http://www.baeldung.com/spring-data-redis-pub-sub) ### Build the Project with Tests Running ``` diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index 25686fca16..6f1fc9294d 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -12,6 +12,7 @@ 4.2.5.RELEASE 1.6.2.RELEASE 0.8.0 + 2.19.1 @@ -72,5 +73,23 @@ ${nosqlunit.version} - + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + + + + + + + diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java index 9a42545d6c..4c55fc3179 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -1,6 +1,5 @@ package com.baeldung.spring.data.redis.queue; - public interface MessagePublisher { void publish(final String message); diff --git a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index f4b3180a37..2a595305bd 100644 --- a/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(final RedisTemplate redisTemplate, - final ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java similarity index 95% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 403cf990e0..01dbfcff4d 100644 --- a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -public class RedisMessageListenerTest { +public class RedisMessageListenerIntegrationTest { @Autowired private RedisMessagePublisher redisMessagePublisher; diff --git a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java similarity index 98% rename from spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index c32dfc7670..1028c0bc24 100644 --- a/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -public class StudentRepositoryTest { +public class StudentRepositoryIntegrationTest { @Autowired private StudentRepository studentRepository; diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index 7dc439206b..4e8828a688 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -12,3 +12,6 @@ The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so i # Viewing the running application To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser + +###Relevant Articles: +- [Guide to Spring Data REST Validators](http://www.baeldung.com/spring-data-rest-validators) diff --git a/spring-exceptions/README.md b/spring-exceptions/README.md index ab6a9643e9..fd9250c6da 100644 --- a/spring-exceptions/README.md +++ b/spring-exceptions/README.md @@ -10,3 +10,4 @@ This project is used to replicate Spring Exceptions only. - [Spring DataIntegrityViolationException](http://www.baeldung.com/spring-dataIntegrityviolationexception) - [Spring BeanDefinitionStoreException](http://www.baeldung.com/spring-beandefinitionstoreexception) - [Spring NoSuchBeanDefinitionException](http://www.baeldung.com/spring-nosuchbeandefinitionexception) +- [Guide to Spring NonTransientDataAccessException](http://www.baeldung.com/nontransientdataaccessexception) diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 733a721c58..12b7e5de79 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -194,7 +194,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -202,27 +202,6 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java index 7a1804ec49..84038e4dcf 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CannotGetJdbcConnectionExceptionTest { +public class CannotGetJdbcConnectionExceptionIntegrationTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java index 357eb168cd..e62a455dd4 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataIntegrityExceptionTest { +public class DataIntegrityExceptionIntegrationTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java similarity index 97% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java index 69b98b0539..8a7c237708 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataRetrievalExceptionTest { +public class DataRetrievalExceptionIntegrationTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java index 036f99ac8f..161bf3252b 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataSourceLookupExceptionTest { +public class DataSourceLookupExceptionIntegrationTest { @Test(expected = DataSourceLookupFailureException.class) public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java similarity index 58% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java index 9c4fd55fa4..316efba0b9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java @@ -16,18 +16,18 @@ import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class InvalidResourceUsageExceptionTest { +public class InvalidResourceUsageExceptionIntegrationTest { - @Autowired - private IFooService fooService; + @Autowired + private IFooService fooService; - @Autowired - private DataSource restDataSource; + @Autowired + private DataSource restDataSource; - @Test(expected = InvalidDataAccessResourceUsageException.class) - public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.execute("revoke select from tutorialuser"); + @Test(expected = InvalidDataAccessResourceUsageException.class) + public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + jdbcTemplate.execute("revoke select from tutorialuser"); try { fooService.findAll(); @@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest { } } - @Test(expected = BadSqlGrammarException.class) - public void whenIncorrectSql_thenBadSqlGrammarException() { - final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); + @Test(expected = BadSqlGrammarException.class) + public void whenIncorrectSql_thenBadSqlGrammarException() { + final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource); - jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); - } + jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class); + } } diff --git a/spring-hibernate3/pom.xml b/spring-hibernate3/pom.xml index 59053be596..9f99d83a42 100644 --- a/spring-hibernate3/pom.xml +++ b/spring-hibernate3/pom.xml @@ -46,7 +46,13 @@ tomcat-dbcp ${tomcat-dbcp.version} - + + + com.h2database + h2 + ${h2.version} + + @@ -127,39 +133,52 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.2.5.RELEASE @@ -170,6 +189,7 @@ 3.6.10.Final 5.1.38 7.0.47 + 1.4.191 1.7.13 diff --git a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java index 15752165cc..fea76dfc70 100644 --- a/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -21,7 +21,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "org.baeldung.persistence.dao", "org.baeldung.persistence.service" }) public class PersistenceConfig { diff --git a/spring-hibernate3/src/main/resources/persistence-h2.properties b/spring-hibernate3/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..d2fcd9545b --- /dev/null +++ b/spring-hibernate3/src/main/resources/persistence-h2.properties @@ -0,0 +1,10 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:spring_hibernate3_01;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 1f18e1d0e8..7888e8b4ee 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -10,6 +10,8 @@ - [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/) +- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) +- [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) ### Quick Start diff --git a/spring-hibernate4/pom.xml b/spring-hibernate4/pom.xml index 4f5cd0c290..d4dabcc274 100644 --- a/spring-hibernate4/pom.xml +++ b/spring-hibernate4/pom.xml @@ -185,7 +185,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -193,27 +193,6 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java index b8b012c061..957207b7e6 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/model/Item.java @@ -4,78 +4,78 @@ import java.io.Serializable; public class Item implements Serializable { - private static final long serialVersionUID = 1L; - private Integer itemId; - private String itemName; - private String itemDescription; - private Integer itemPrice; + private static final long serialVersionUID = 1L; + private Integer itemId; + private String itemName; + private String itemDescription; + private Integer itemPrice; - // constructors - public Item() { + // constructors + public Item() { - } + } - public Item(final Integer itemId, final String itemName, final String itemDescription) { - super(); - this.itemId = itemId; - this.itemName = itemName; - this.itemDescription = itemDescription; - } + public Item(final Integer itemId, final String itemName, final String itemDescription) { + super(); + this.itemId = itemId; + this.itemName = itemName; + this.itemDescription = itemDescription; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Item other = (Item) obj; - if (itemId == null) { - if (other.itemId != null) - return false; - } else if (!itemId.equals(other.itemId)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Item other = (Item) obj; + if (itemId == null) { + if (other.itemId != null) + return false; + } else if (!itemId.equals(other.itemId)) + return false; + return true; + } - public Integer getItemId() { - return itemId; - } + public Integer getItemId() { + return itemId; + } - public void setItemId(final Integer itemId) { - this.itemId = itemId; - } + public void setItemId(final Integer itemId) { + this.itemId = itemId; + } - public String getItemName() { - return itemName; - } + public String getItemName() { + return itemName; + } - public void setItemName(final String itemName) { - this.itemName = itemName; - } + public void setItemName(final String itemName) { + this.itemName = itemName; + } - public String getItemDescription() { - return itemDescription; - } + public String getItemDescription() { + return itemDescription; + } - public Integer getItemPrice() { - return itemPrice; - } + public Integer getItemPrice() { + return itemPrice; + } - public void setItemPrice(final Integer itemPrice) { - this.itemPrice = itemPrice; - } + public void setItemPrice(final Integer itemPrice) { + this.itemPrice = itemPrice; + } - public void setItemDescription(final String itemDescription) { - this.itemDescription = itemDescription; - } + public void setItemDescription(final String itemDescription) { + this.itemDescription = itemDescription; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java index 57f32cfe50..ff9ccb017b 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/util/HibernateUtil.java @@ -5,16 +5,15 @@ import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { - + @SuppressWarnings("deprecation") public static Session getHibernateSession() { - final SessionFactory sf = new Configuration() - .configure("criteria.cfg.xml").buildSessionFactory(); + final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory(); - // factory = new Configuration().configure().buildSessionFactory(); - final Session session = sf.openSession(); - return session; + // factory = new Configuration().configure().buildSessionFactory(); + final Session session = sf.openSession(); + return session; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 4db94f2ad7..83e3c2f9a5 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil; public class ApplicationView { - // default Constructor - public ApplicationView() { + // default Constructor + public ApplicationView() { - } + } - public boolean checkIfCriteriaTimeLower() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - Transaction tx = null; - - // calculate the time taken by criteria - final long startTimeCriteria = System.nanoTime(); - cr.add(Restrictions.like("itemName", "%item One%")); - final List results = cr.list(); - final long endTimeCriteria = System.nanoTime(); - final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; + public boolean checkIfCriteriaTimeLower() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + Transaction tx = null; - // calculate the time taken by HQL - final long startTimeHQL = System.nanoTime(); - tx = session.beginTransaction(); - final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); - final long endTimeHQL = System.nanoTime(); - final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; + // calculate the time taken by criteria + final long startTimeCriteria = System.nanoTime(); + cr.add(Restrictions.like("itemName", "%item One%")); + final List results = cr.list(); + final long endTimeCriteria = System.nanoTime(); + final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000; - if (durationCriteria > durationHQL) { - return false; - } else { - return true; - } - } + // calculate the time taken by HQL + final long startTimeHQL = System.nanoTime(); + tx = session.beginTransaction(); + final List items = session.createQuery("FROM Item where itemName like '%item One%'").list(); + final long endTimeHQL = System.nanoTime(); + final long durationHQL = (endTimeHQL - startTimeHQL) / 1000; - // To get items having price more than 1000 - public String[] greaterThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.gt("itemPrice", 1000)); - final List greaterThanItemsList = cr.list(); - final String greaterThanItems[] = new String[greaterThanItemsList.size()]; - for (int i = 0; i < greaterThanItemsList.size(); i++) { - greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); - } - session.close(); - return greaterThanItems; - } + if (durationCriteria > durationHQL) { + return false; + } else { + return true; + } + } - // To get items having price less than 1000 - public String[] lessThanCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.lt("itemPrice", 1000)); - final List lessThanItemsList = cr.list(); - final String lessThanItems[] = new String[lessThanItemsList.size()]; - for (int i = 0; i < lessThanItemsList.size(); i++) { - lessThanItems[i] = lessThanItemsList.get(i).getItemName(); - } - session.close(); - return lessThanItems; - } + // To get items having price more than 1000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.gt("itemPrice", 1000)); + final List greaterThanItemsList = cr.list(); + final String greaterThanItems[] = new String[greaterThanItemsList.size()]; + for (int i = 0; i < greaterThanItemsList.size(); i++) { + greaterThanItems[i] = greaterThanItemsList.get(i).getItemName(); + } + session.close(); + return greaterThanItems; + } - // To get items whose Name start with Chair - public String[] likeCriteria() { - final Session session = HibernateUtil.getHibernateSession(); + // To get items having price less than 1000 + public String[] lessThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.lt("itemPrice", 1000)); + final List lessThanItemsList = cr.list(); + final String lessThanItems[] = new String[lessThanItemsList.size()]; + for (int i = 0; i < lessThanItemsList.size(); i++) { + lessThanItems[i] = lessThanItemsList.get(i).getItemName(); + } + session.close(); + return lessThanItems; + } - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.like("itemName", "%chair%")); - final List likeItemsList = cr.list(); - final String likeItems[] = new String[likeItemsList.size()]; - for (int i = 0; i < likeItemsList.size(); i++) { - likeItems[i] = likeItemsList.get(i).getItemName(); - } - session.close(); - return likeItems; - } + // To get items whose Name start with Chair + public String[] likeCriteria() { + final Session session = HibernateUtil.getHibernateSession(); - // Case sensitive search - public String[] likeCaseCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.ilike("itemName", "%Chair%")); - final List ilikeItemsList = cr.list(); - final String ilikeItems[] = new String[ilikeItemsList.size()]; - for (int i = 0; i < ilikeItemsList.size(); i++) { - ilikeItems[i] = ilikeItemsList.get(i).getItemName(); - } - session.close(); - return ilikeItems; - } + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.like("itemName", "%chair%")); + final List likeItemsList = cr.list(); + final String likeItems[] = new String[likeItemsList.size()]; + for (int i = 0; i < likeItemsList.size(); i++) { + likeItems[i] = likeItemsList.get(i).getItemName(); + } + session.close(); + return likeItems; + } - // To get records having itemPrice in between 100 and 200 - public String[] betweenCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - // To get items having price more than 1000 - cr.add(Restrictions.between("itemPrice", 100, 200)); - final List betweenItemsList = cr.list(); - final String betweenItems[] = new String[betweenItemsList.size()]; - for (int i = 0; i < betweenItemsList.size(); i++) { - betweenItems[i] = betweenItemsList.get(i).getItemName(); - } - session.close(); - return betweenItems; - } + // Case sensitive search + public String[] likeCaseCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.ilike("itemName", "%Chair%")); + final List ilikeItemsList = cr.list(); + final String ilikeItems[] = new String[ilikeItemsList.size()]; + for (int i = 0; i < ilikeItemsList.size(); i++) { + ilikeItems[i] = ilikeItemsList.get(i).getItemName(); + } + session.close(); + return ilikeItems; + } - // To check if the given property is null - public String[] nullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - final List nullItemsList = cr.list(); - final String nullDescItems[] = new String[nullItemsList.size()]; - for (int i = 0; i < nullItemsList.size(); i++) { - nullDescItems[i] = nullItemsList.get(i).getItemName(); - } - session.close(); - return nullDescItems; - } + // To get records having itemPrice in between 100 and 200 + public String[] betweenCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + // To get items having price more than 1000 + cr.add(Restrictions.between("itemPrice", 100, 200)); + final List betweenItemsList = cr.list(); + final String betweenItems[] = new String[betweenItemsList.size()]; + for (int i = 0; i < betweenItemsList.size(); i++) { + betweenItems[i] = betweenItemsList.get(i).getItemName(); + } + session.close(); + return betweenItems; + } - // To check if the given property is not null - public String[] notNullCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNotNull("itemDescription")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is null + public String[] nullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + final List nullItemsList = cr.list(); + final String nullDescItems[] = new String[nullItemsList.size()]; + for (int i = 0; i < nullItemsList.size(); i++) { + nullDescItems[i] = nullItemsList.get(i).getItemName(); + } + session.close(); + return nullDescItems; + } - // Adding more than one expression in one cr - public String[] twoCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.add(Restrictions.isNull("itemDescription")); - cr.add(Restrictions.like("itemName", "chair%")); - final List notNullItemsList = cr.list(); - final String notNullDescItems[] = new String[notNullItemsList.size()]; - for (int i = 0; i < notNullItemsList.size(); i++) { - notNullDescItems[i] = notNullItemsList.get(i).getItemName(); - } - session.close(); - return notNullDescItems; - } + // To check if the given property is not null + public String[] notNullCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNotNull("itemDescription")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical AND - public String[] andLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); - cr.add(andExample); - final List andItemsList = cr.list(); - final String andItems[] = new String[andItemsList.size()]; - for (int i = 0; i < andItemsList.size(); i++) { - andItems[i] = andItemsList.get(i).getItemName(); - } - session.close(); - return andItems; - } + // Adding more than one expression in one cr + public String[] twoCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.add(Restrictions.isNull("itemDescription")); + cr.add(Restrictions.like("itemName", "chair%")); + final List notNullItemsList = cr.list(); + final String notNullDescItems[] = new String[notNullItemsList.size()]; + for (int i = 0; i < notNullItemsList.size(); i++) { + notNullDescItems[i] = notNullItemsList.get(i).getItemName(); + } + session.close(); + return notNullDescItems; + } - // To get items matching with the above defined conditions joined - // with Logical OR - public String[] orLogicalCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); - final Criterion chairItems = Restrictions.like("itemName", "Chair%"); - final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); - cr.add(orExample); - final List orItemsList = cr.list(); - final String orItems[] = new String[orItemsList.size()]; - for (int i = 0; i < orItemsList.size(); i++) { - orItems[i] = orItemsList.get(i).getItemName(); - } - session.close(); - return orItems; - } + // To get items matching with the above defined conditions joined + // with Logical AND + public String[] andLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems); + cr.add(andExample); + final List andItemsList = cr.list(); + final String andItems[] = new String[andItemsList.size()]; + for (int i = 0; i < andItemsList.size(); i++) { + andItems[i] = andItemsList.get(i).getItemName(); + } + session.close(); + return andItems; + } - // Sorting example - public String[] sortingCriteria() { - final Session session = HibernateUtil.getHibernateSession(); - final Criteria cr = session.createCriteria(Item.class); - cr.addOrder(Order.asc("itemName")); - cr.addOrder(Order.desc("itemPrice")).list(); - final List sortedItemsList = cr.list(); - final String sortedItems[] = new String[sortedItemsList.size()]; - for (int i = 0; i < sortedItemsList.size(); i++) { - sortedItems[i] = sortedItemsList.get(i).getItemName(); - } - session.close(); - return sortedItems; - } + // To get items matching with the above defined conditions joined + // with Logical OR + public String[] orLogicalCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); + final Criterion chairItems = Restrictions.like("itemName", "Chair%"); + final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); + cr.add(orExample); + final List orItemsList = cr.list(); + final String orItems[] = new String[orItemsList.size()]; + for (int i = 0; i < orItemsList.size(); i++) { + orItems[i] = orItemsList.get(i).getItemName(); + } + session.close(); + return orItems; + } - // Set projections Row Count - public Long[] projectionRowCount() { - final Session session = HibernateUtil.getHibernateSession(); - final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()) - .list(); - final Long projectedRowCount[] = new Long[itemProjected.size()]; - for (int i = 0; i < itemProjected.size(); i++) { - projectedRowCount[i] = itemProjected.get(i); - } - session.close(); - return projectedRowCount; - } + // Sorting example + public String[] sortingCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final Criteria cr = session.createCriteria(Item.class); + cr.addOrder(Order.asc("itemName")); + cr.addOrder(Order.desc("itemPrice")).list(); + final List sortedItemsList = cr.list(); + final String sortedItems[] = new String[sortedItemsList.size()]; + for (int i = 0; i < sortedItemsList.size(); i++) { + sortedItems[i] = sortedItemsList.get(i).getItemName(); + } + session.close(); + return sortedItems; + } - // Set projections average of itemPrice - public Double[] projectionAverage() { - final Session session = HibernateUtil.getHibernateSession(); - final List avgItemPriceList = session.createCriteria(Item.class) - .setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + // Set projections Row Count + public Long[] projectionRowCount() { + final Session session = HibernateUtil.getHibernateSession(); + final List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); + final Long projectedRowCount[] = new Long[itemProjected.size()]; + for (int i = 0; i < itemProjected.size(); i++) { + projectedRowCount[i] = itemProjected.get(i); + } + session.close(); + return projectedRowCount; + } - final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; - for (int i = 0; i < avgItemPriceList.size(); i++) { - avgItemPrice[i] = (Double) avgItemPriceList.get(i); - } - session.close(); - return avgItemPrice; - } + // Set projections average of itemPrice + public Double[] projectionAverage() { + final Session session = HibernateUtil.getHibernateSession(); + final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); + + final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; + for (int i = 0; i < avgItemPriceList.size(); i++) { + avgItemPrice[i] = (Double) avgItemPriceList.get(i); + } + session.close(); + return avgItemPrice; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java index ec8dc32200..f4a9b8a678 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/OrderDetail.java @@ -5,54 +5,54 @@ import java.io.Serializable; import java.sql.Date; @Entity -@Table (name = "USER_ORDER") -public class OrderDetail implements Serializable{ +@Table(name = "USER_ORDER") +public class OrderDetail implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="ORDER_ID") - private Long orderId; - - public OrderDetail(){ - } - - public OrderDetail(Date orderDate, String orderDesc) { - super(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrderDetail other = (OrderDetail) obj; - if (orderId == null) { - if (other.orderId != null) - return false; - } else if (!orderId.equals(other.orderId)) - return false; - - return true; - } + private static final long serialVersionUID = 1L; - public Long getOrderId() { - return orderId; - } - public void setOrderId(Long orderId) { - this.orderId = orderId; - } + @Id + @GeneratedValue + @Column(name = "ORDER_ID") + private Long orderId; + + public OrderDetail() { + } + + public OrderDetail(Date orderDate, String orderDesc) { + super(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrderDetail other = (OrderDetail) obj; + if (orderId == null) { + if (other.orderId != null) + return false; + } else if (!orderId.equals(other.orderId)) + return false; + + return true; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } } - - diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java index 22b4fdc76c..2559d5f048 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserEager.java @@ -6,66 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserEager implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserEager() { - } + private static final long serialVersionUID = 1L; - public UserEager(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserEager other = (UserEager) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserEager() { + } - public Long getUserId() { - return userId; - } + public UserEager(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserEager other = (UserEager) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java index 5038fb90ef..5852e74418 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/model/UserLazy.java @@ -6,67 +6,66 @@ import java.util.HashSet; import java.util.Set; @Entity -@Table (name = "USER") +@Table(name = "USER") public class UserLazy implements Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue - @Column(name="USER_ID") - private Long userId; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") - private Set orderDetail = new HashSet(); - public UserLazy() { - } + private static final long serialVersionUID = 1L; - public UserLazy(final Long userId) { - super(); - this.userId = userId; - } + @Id + @GeneratedValue + @Column(name = "USER_ID") + private Long userId; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set orderDetail = new HashSet(); - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final UserLazy other = (UserLazy) obj; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } + public UserLazy() { + } - public Long getUserId() { - return userId; - } + public UserLazy(final Long userId) { + super(); + this.userId = userId; + } - public void setUserId(final Long userId) { - this.userId = userId; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - - public Set getOrderDetail() { - return orderDetail; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final UserLazy other = (UserLazy) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } - public void setOrderDetail(Set orderDetail) { - this.orderDetail = orderDetail; - } + public Long getUserId() { + return userId; + } + + public void setUserId(final Long userId) { + this.userId = userId; + } + + public Set getOrderDetail() { + return orderDetail; + } + + public void setOrderDetail(Set orderDetail) { + this.orderDetail = orderDetail; + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java index bbd7729232..c7be96abb7 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/fetching/util/HibernateUtil.java @@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration; public class HibernateUtil { - @SuppressWarnings("deprecation") - public static Session getHibernateSession(String fetchMethod) { - //two config files are there - //one with lazy loading enabled - //another lazy = false - SessionFactory sf; - if ("lazy".equals(fetchMethod)) { - sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); - } else { - sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); - } - - // fetching.cfg.xml is used for this example - return sf.openSession(); - } + @SuppressWarnings("deprecation") + public static Session getHibernateSession(String fetchMethod) { + // two config files are there + // one with lazy loading enabled + // another lazy = false + SessionFactory sf; + if ("lazy".equals(fetchMethod)) { + sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); + } else { + sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); + } + + // fetching.cfg.xml is used for this example + return sf.openSession(); + } public static Session getHibernateSession() { - return new Configuration() - .configure("fetching.cfg.xml") - .buildSessionFactory() - .openSession(); + return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession(); } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java index bdd48d6aa6..d36a1e58cf 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java @@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; -@NamedNativeQueries({ - @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), - @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) +@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) @Entity @Audited // @Proxy(lazy = false) public class Foo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); - public Foo() { - super(); - } + public Foo() { + super(); + } - public Foo(final String name) { - super(); - this.name = name; - } + public Foo(final String name) { + super(); + this.name = name; + } - // + // - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(final Bar bar) { - this.bar = bar; - } + public void setBar(final Bar bar) { + this.bar = bar; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - // + // - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java new file mode 100644 index 0000000000..2275bf14f2 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -0,0 +1,183 @@ +package com.baeldung.hibernate.criteria; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.hibernate.Session; +import org.junit.Test; + +import com.baeldung.hibernate.criteria.model.Item; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import com.baeldung.hibernate.criteria.view.ApplicationView; + +public class HibernateCriteriaIntegrationTest { + + final private ApplicationView av = new ApplicationView(); + + @Test + public void testPerformanceOfCriteria() { + assertTrue(av.checkIfCriteriaTimeLower()); + } + + @Test + public void testLikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); + final String expectedLikeItems[] = new String[expectedLikeList.size()]; + for (int i = 0; i < expectedLikeList.size(); i++) { + expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLikeItems, av.likeCriteria()); + } + + @Test + public void testILikeCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); + final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; + for (int i = 0; i < expectedChairCaseList.size(); i++) { + expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); + + } + + @Test + public void testNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list(); + final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { + expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); + } + + @Test + public void testIsNotNullCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list(); + final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; + for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { + expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); + + } + + @Test + public void testAverageProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list(); + + final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; + for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { + expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); + + } + + @Test + public void testRowCountProjection() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); + final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; + for (int i = 0; i < expectedCountProjItemsList.size(); i++) { + expectedCountProjItems[i] = expectedCountProjItemsList.get(i); + } + session.close(); + assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); + } + + @Test + public void testOrCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); + final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; + for (int i = 0; i < expectedOrCritItemsList.size(); i++) { + expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); + } + + @Test + public void testAndCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); + final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; + for (int i = 0; i < expectedAndCritItemsList.size(); i++) { + expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); + } + + @Test + public void testMultiCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); + final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; + for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { + expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); + } + + @Test + public void testSortCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list(); + final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; + for (int i = 0; i < expectedSortCritItemsList.size(); i++) { + expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); + } + + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); + final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); + } + + @Test + public void testLessThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); + final String expectedLessThanItems[] = new String[expectedLessList.size()]; + for (int i = 0; i < expectedLessList.size(); i++) { + expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); + } + + @Test + public void betweenCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list(); + final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; + for (int i = 0; i < expectedBetweenList.size(); i++) { + expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java deleted file mode 100644 index 3bd8c5ee00..0000000000 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.baeldung.hibernate.criteria; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.hibernate.Session; -import org.junit.Test; - -import com.baeldung.hibernate.criteria.model.Item; -import com.baeldung.hibernate.criteria.util.HibernateUtil; -import com.baeldung.hibernate.criteria.view.ApplicationView; - -public class HibernateCriteriaTest { - - final private ApplicationView av = new ApplicationView(); - - @Test - public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); - } - - @Test - public void testLikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list(); - final String expectedLikeItems[] = new String[expectedLikeList.size()]; - for (int i = 0; i < expectedLikeList.size(); i++) { - expectedLikeItems[i] = expectedLikeList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLikeItems, av.likeCriteria()); - } - - @Test - public void testILikeCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list(); - final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()]; - for (int i = 0; i < expectedChairCaseList.size(); i++) { - expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria()); - - } - - @Test - public void testNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null") - .list(); - final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) { - expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNullDescItems, av.nullCriteria()); - } - - @Test - public void testIsNotNullCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedIsNotNullDescItemsList = session - .createQuery("From Item where itemDescription is not null").list(); - final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()]; - for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) { - expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria()); - - } - - @Test - public void testAverageProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item") - .list(); - - final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()]; - for (int i = 0; i < expectedAvgProjItemsList.size(); i++) { - expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedAvgProjItems, av.projectionAverage()); - - } - - @Test - public void testRowCountProjection() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list(); - final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()]; - for (int i = 0; i < expectedCountProjItemsList.size(); i++) { - expectedCountProjItems[i] = expectedCountProjItemsList.get(i); - } - session.close(); - assertArrayEquals(expectedCountProjItems, av.projectionRowCount()); - } - - @Test - public void testOrCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedOrCritItemsList = session - .createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list(); - final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()]; - for (int i = 0; i < expectedOrCritItemsList.size(); i++) { - expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria()); - } - - @Test - public void testAndCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedAndCritItemsList = session - .createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list(); - final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()]; - for (int i = 0; i < expectedAndCritItemsList.size(); i++) { - expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria()); - } - - @Test - public void testMultiCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedMultiCritItemsList = session - .createQuery("From Item where itemDescription is null and itemName like'chair%'").list(); - final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()]; - for (int i = 0; i < expectedMultiCritItemsList.size(); i++) { - expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedMultiCritItems, av.twoCriteria()); - } - - @Test - public void testSortCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedSortCritItemsList = session - .createQuery("From Item order by itemName asc, itemPrice desc").list(); - final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()]; - for (int i = 0; i < expectedSortCritItemsList.size(); i++) { - expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedSortCritItems, av.sortingCriteria()); - } - - @Test - public void testGreaterThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list(); - final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()]; - for (int i = 0; i < expectedGreaterThanList.size(); i++) { - expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria()); - } - - @Test - public void testLessThanCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedLessList = session.createQuery("From Item where itemPrice<1000").list(); - final String expectedLessThanItems[] = new String[expectedLessList.size()]; - for (int i = 0; i < expectedLessList.size(); i++) { - expectedLessThanItems[i] = expectedLessList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedLessThanItems, av.lessThanCriteria()); - } - - @Test - public void betweenCriteriaQuery() { - final Session session = HibernateUtil.getHibernateSession(); - final List expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200") - .list(); - final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()]; - for (int i = 0; i < expectedBetweenList.size(); i++) { - expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName(); - } - session.close(); - assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); - } -} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java index 8341df9fcb..99164efb7a 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestRunner.java @@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure; public class HibernateCriteriaTestRunner { - public static void main(final String[] args) { - Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); - for (Failure failure : result.getFailures()) { - - } - } + public static void main(final String[] args) { + Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class); + for (Failure failure : result.getFailures()) { + + } + } } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java index ab27a6ba82..dc1040734f 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaTestSuite.java @@ -4,8 +4,8 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({ HibernateCriteriaTest.class }) +@Suite.SuiteClasses({ HibernateCriteriaIntegrationTest.class }) public class HibernateCriteriaTestSuite { - + } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java new file mode 100644 index 0000000000..65bf36f8bf --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.fetching; + +import com.baeldung.hibernate.fetching.model.OrderDetail; +import com.baeldung.hibernate.fetching.view.FetchingAppView; +import org.hibernate.Hibernate; +import org.junit.Before; +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class HibernateFetchingIntegrationTest { + + // this loads sample data in the database + @Before + public void addFecthingTestData() { + FetchingAppView fav = new FetchingAppView(); + fav.createTestData(); + } + + // testLazyFetching() tests the lazy loading + // Since it lazily loaded so orderDetalSetLazy won't + // be initialized + @Test + public void testLazyFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetLazy = fav.lazyLoaded(); + assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); + } + + // testEagerFetching() tests the eager loading + // Since it eagerly loaded so orderDetalSetLazy would + // be initialized + @Test + public void testEagerFetching() { + FetchingAppView fav = new FetchingAppView(); + Set orderDetalSetEager = fav.eagerLoaded(); + assertTrue(Hibernate.isInitialized(orderDetalSetEager)); + } +} diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java deleted file mode 100644 index a650f8eb37..0000000000 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/fetching/HibernateFetchingTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.hibernate.fetching; - -import com.baeldung.hibernate.fetching.model.OrderDetail; -import com.baeldung.hibernate.fetching.view.FetchingAppView; -import org.hibernate.Hibernate; -import org.junit.Before; -import org.junit.Test; - -import java.util.Set; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class HibernateFetchingTest { - - - //this loads sample data in the database - @Before - public void addFecthingTestData(){ - FetchingAppView fav = new FetchingAppView(); - fav.createTestData(); - } - - //testLazyFetching() tests the lazy loading - //Since it lazily loaded so orderDetalSetLazy won't - //be initialized - @Test - public void testLazyFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetLazy = fav.lazyLoaded(); - assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); - } - - //testEagerFetching() tests the eager loading - //Since it eagerly loaded so orderDetalSetLazy would - //be initialized - @Test - public void testEagerFetching() { - FetchingAppView fav = new FetchingAppView(); - Set orderDetalSetEager = fav.eagerLoaded(); - assertTrue(Hibernate.isInitialized(orderDetalSetEager)); - } -} diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java index 8a8a3445f6..34c725d62b 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/AuditTestSuite.java @@ -5,9 +5,9 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - EnversFooBarAuditTest.class, - JPABarAuditTest.class, - SpringDataJPABarAuditTest.class + EnversFooBarAuditIntegrationTest.class, + JPABarAuditIntegrationTest.class, + SpringDataJPABarAuditIntegrationTest.class }) // @formatter:on public class AuditTestSuite { // diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java similarity index 98% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 6c13816b63..ed2e111c8f 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -28,9 +28,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class EnversFooBarAuditTest { +public class EnversFooBarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java similarity index 97% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java index 1e4a10f61c..b63a4b989b 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/JPABarAuditIntegrationTest.java @@ -27,9 +27,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class JPABarAuditTest { +public class JPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(JPABarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(JPABarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java similarity index 96% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java index 05c0e9fa83..e794b282f6 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/SpringDataJPABarAuditIntegrationTest.java @@ -26,9 +26,9 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class SpringDataJPABarAuditTest { +public class SpringDataJPABarAuditIntegrationTest { - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditTest.class); + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); @BeforeClass public static void setUpBeforeClass() throws Exception { diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java index aadaefbe44..2e729c5680 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/save/SaveMethodsTest.java @@ -1,6 +1,5 @@ package com.baeldung.persistence.save; - import com.baeldung.persistence.model.Person; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -25,16 +24,9 @@ public class SaveMethodsTest { @BeforeClass public static void beforeTests() { - Configuration configuration = new Configuration() - .addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( - configuration.getProperties()).build(); + Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } @@ -44,7 +36,6 @@ public class SaveMethodsTest { session.beginTransaction(); } - @Test public void whenPersistTransient_thenSavedToDatabaseOnCommit() { @@ -244,7 +235,6 @@ public class SaveMethodsTest { assertNotNull(session.get(Person.class, person.getId())); - } @Test diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java index 238b228101..db64107405 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java @@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo; import com.baeldung.spring.PersistenceConfig; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooStoredProceduresIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); @@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getFoosByNameExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest { private boolean getAllFoosExists() { try { - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") - .addEntity(Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); sqlQuery.list(); return true; } catch (SQLGrammarException e) { @@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo(randomAlphabetic(6))); // Stored procedure getAllFoos using createSQLQuery - Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity( - Foo.class); + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); @SuppressWarnings("unchecked") List allFoos = sqlQuery.list(); for (Foo foo : allFoos) { @@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest { fooService.create(new Foo("NewFooName")); // Stored procedure getFoosByName using createSQLQuery() - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)") - .addEntity(Foo.class).setParameter("fooName", "NewFooName"); + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName = sqlQuery.list(); for (Foo foo : allFoosByName) { @@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest { } // Stored procedure getFoosByName using getNamedQuery() - Query namedQuery = session.getNamedQuery("callGetFoosByName") - .setParameter("fooName", "NewFooName"); + Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); @SuppressWarnings("unchecked") List allFoosByName2 = namedQuery.list(); for (Foo foo : allFoosByName2) { diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 8f78469989..8e83f82f38 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -11,6 +11,7 @@ 4.3.2.RELEASE 5.12.0 + 4.12 @@ -26,6 +27,12 @@ activemq-all ${activemq.version} + + junit + junit + ${junit.version} + test + @@ -36,8 +43,8 @@ maven-compiler-plugin 3.2 - 1.7 - 1.7 + 1.8 + 1.8 @@ -52,6 +59,16 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + spring-jms - \ No newline at end of file + diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java index 4da02907a9..ff4f262b38 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java @@ -18,6 +18,6 @@ public class Employee { } public String toString() { - return "Person: name(" + name + "), age(" + age + ")"; + return "Employee: name(" + name + "), age(" + age + ")"; } } diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java deleted file mode 100644 index a243bc1390..0000000000 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.spring.jms; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import java.net.URI; - -public class SampleJMSExample { - public static void main(String[] args) throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:61616)")); - broker.start(); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); - - } -} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java index 865a1d4747..927762f05b 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -1,17 +1,18 @@ package com.baeldung.spring.jms; import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; -import javax.jms.*; +import javax.jms.Queue; +import java.util.HashMap; +import java.util.Map; public class SampleJmsMessageSender { private JmsTemplate jmsTemplate; private Queue queue; - public void createJmsTemplate(ConnectionFactory cf) { - this.jmsTemplate = new JmsTemplate(cf); + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; } public void setQueue(Queue queue) { @@ -19,10 +20,10 @@ public class SampleJmsMessageSender { } public void simpleSend() { - this.jmsTemplate.send(this.queue, new MessageCreator() { - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("hello queue world"); - } - }); + jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world")); } -} \ No newline at end of file + + public void sendMessage(final Employee employee) { + this.jmsTemplate.convertAndSend(employee); + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java index 0320870d88..f35c22e144 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -1,23 +1,40 @@ package com.baeldung.spring.jms; +import org.springframework.jms.core.JmsTemplate; + import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; +import javax.jms.Queue; import javax.jms.TextMessage; +import java.util.Map; public class SampleListener implements MessageListener { - private String textMessage; + private JmsTemplate jmsTemplate; + private Queue queue; + + public void setJmsTemplate(JmsTemplate jmsTemplate) { + this.jmsTemplate = jmsTemplate; + } + + public void setQueue(Queue queue) { + this.queue = queue; + } public void onMessage(Message message) { if (message instanceof TextMessage) { try { - textMessage = ((TextMessage) message).getText(); + String msg = ((TextMessage) message).getText(); + System.out.println("Received message: " + msg); } catch (JMSException ex) { throw new RuntimeException(ex); } - } else { - throw new IllegalArgumentException("Message Error"); } } -} \ No newline at end of file + + public Employee receiveMessage() throws JMSException { + Map map = (Map) this.jmsTemplate.receiveAndConvert(); + return new Employee((String) map.get("name"), (Integer) map.get("age")); + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java index 6cfc588f13..368a62841f 100644 --- a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java @@ -11,10 +11,10 @@ import javax.jms.Session; public class SampleMessageConverter implements MessageConverter { public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { - Employee person = (Employee) object; + Employee employee = (Employee) object; MapMessage message = session.createMapMessage(); - message.setString("name", person.getName()); - message.setInt("age", person.getAge()); + message.setString("name", employee.getName()); + message.setInt("age", employee.getAge()); return message; } diff --git a/spring-jms/src/main/resources/EmbeddedActiveMQ.xml b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml new file mode 100644 index 0000000000..016b07e831 --- /dev/null +++ b/spring-jms/src/main/resources/EmbeddedActiveMQ.xml @@ -0,0 +1,18 @@ + + + + + + + + + + diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml index c15289763f..28bf848e59 100644 --- a/spring-jms/src/main/resources/applicationContext.xml +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -1,30 +1,51 @@ + xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd + http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd"> - - - + - + + + + + + + + + + + + + + + + + - + + + - + + + + + - + - - \ No newline at end of file + diff --git a/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java new file mode 100644 index 0000000000..c0761939ad --- /dev/null +++ b/spring-jms/src/test/java/com/baeldung/spring/jms/DefaultTextMessageSenderTest.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.jms; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DefaultTextMessageSenderTest { + + private static SampleJmsMessageSender messageProducer; + + @SuppressWarnings("resource") + @BeforeClass + public static void setUp() { + ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml"); + messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender"); + } + + @Test + public void testSimpleSend() { + messageProducer.simpleSend(); + } + +} diff --git a/jooq-spring/.gitignore b/spring-jooq/.gitignore similarity index 100% rename from jooq-spring/.gitignore rename to spring-jooq/.gitignore diff --git a/spring-jooq/README.md b/spring-jooq/README.md new file mode 100644 index 0000000000..79718e74c6 --- /dev/null +++ b/spring-jooq/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [Spring Boot Support for jOOQ](http://www.baeldung.com/spring-boot-support-for-jooq) +- [Introduction to jOOQ with Spring](http://www.baeldung.com/jooq-with-spring) diff --git a/jooq-spring/pom.xml b/spring-jooq/pom.xml similarity index 72% rename from jooq-spring/pom.xml rename to spring-jooq/pom.xml index e77ff0cbfd..96a3de11db 100644 --- a/jooq-spring/pom.xml +++ b/spring-jooq/pom.xml @@ -161,9 +161,55 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 3.7.3 1.4.191 @@ -173,6 +219,7 @@ 4.12 3.5.1 + 2.19.1 \ No newline at end of file diff --git a/jooq-spring/src/main/resources/application.properties b/spring-jooq/src/main/resources/application.properties similarity index 100% rename from jooq-spring/src/main/resources/application.properties rename to spring-jooq/src/main/resources/application.properties diff --git a/jooq-spring/src/main/resources/intro_config.properties b/spring-jooq/src/main/resources/intro_config.properties similarity index 100% rename from jooq-spring/src/main/resources/intro_config.properties rename to spring-jooq/src/main/resources/intro_config.properties diff --git a/jooq-spring/src/main/resources/intro_schema.sql b/spring-jooq/src/main/resources/intro_schema.sql similarity index 100% rename from jooq-spring/src/main/resources/intro_schema.sql rename to spring-jooq/src/main/resources/intro_schema.sql diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java similarity index 98% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java index df628f9f78..06290ae8db 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java +++ b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java @@ -22,7 +22,7 @@ import javax.sql.DataSource; @ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" }) @EnableTransactionManagement @PropertySource("classpath:intro_config.properties") -public class PersistenceContext { +public class PersistenceContextIntegrationTest { @Autowired private Environment environment; diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java similarity index 97% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java index 68f975dd6d..28bc4c63c7 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java +++ b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java @@ -17,10 +17,10 @@ import static com.baeldung.jooq.introduction.db.public_.tables.AuthorBook.AUTHOR import static com.baeldung.jooq.introduction.db.public_.tables.Book.BOOK; import static org.junit.Assert.assertEquals; -@ContextConfiguration(classes = PersistenceContext.class) +@ContextConfiguration(classes = PersistenceContextIntegrationTest.class) @Transactional(transactionManager = "transactionManager") @RunWith(SpringJUnit4ClassRunner.class) -public class QueryTest { +public class QueryIntegrationTest { @Autowired private DSLContext dsl; diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java similarity index 99% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java index f9427f30fb..fa3f342ecd 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java +++ b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; @SpringApplicationConfiguration(Application.class) @Transactional("transactionManager") @RunWith(SpringJUnit4ClassRunner.class) -public class SpringBootTest { +public class SpringBootIntegrationTest { @Autowired private DSLContext dsl; diff --git a/spring-jpa/README.md b/spring-jpa/README.md index f974c6e22c..4568c0bc7f 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -10,3 +10,5 @@ - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) - [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) +- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index ebb9c5bc83..cf0c2246af 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -182,7 +182,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -190,31 +190,10 @@ - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - + 4.3.2.RELEASE diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index f97f53b82c..907043b8ce 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest { final Foo foo = new Foo(randomAlphabetic(6)); fooService.create(foo); fooService.findOne(foo.getId()); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest { return nativeQuery.executeUpdate(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @Test public final void givenCacheableQueryIsExecuted_thenItIsCached() { new TransactionTemplate(platformTransactionManager).execute(status -> { - return entityManager.createQuery("select f from Foo f") - .setHint("org.hibernate.cacheable", true) - .getResultList(); + return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0) - .getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize(); assertThat(size, greaterThan(0)); } } diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 892aaf24f1..e2e3ea6f97 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -3,11 +3,12 @@ org.springframework.samples spring-katharsis 0.0.1-SNAPSHOT + war org.springframework.boot spring-boot-starter-parent - 1.2.6.RELEASE + 1.3.3.RELEASE @@ -62,6 +63,7 @@ 1.8 1.0.0 2.4.0 + 1.6.0 @@ -71,7 +73,100 @@ org.springframework.boot spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index 1b409f8b91..e7beb16e04 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -2,9 +2,10 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 67e4c6ae1d..58a92002c8 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -30,7 +30,7 @@ public class User { private String email; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) @JsonApiToMany @JsonApiIncludeByDefault private Set roles; diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index 25d4559e3d..b55fdbba03 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -3,4 +3,7 @@ spring.datasource.username = sa spring.datasource.password = spring.jpa.show-sql = false spring.jpa.hibernate.ddl-auto = create-drop -spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect + +server.port=8082 +server.context-path=/spring-katharsis \ No newline at end of file diff --git a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java b/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java index bbddba3490..26a8c42a25 100644 --- a/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java +++ b/spring-katharsis/src/test/java/org/baeldung/test/JsonApiLiveTest.java @@ -2,22 +2,14 @@ package org.baeldung.test; import static org.junit.Assert.assertEquals; -import org.baeldung.Application; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebAppConfiguration public class JsonApiLiveTest { - private final static String URL_PREFIX = "http://localhost:8080/users"; + private final static String URL_PREFIX = "http://localhost:8082/spring-katharsis/users"; @Test public void whenGettingAllUsers_thenCorrect() { diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 3dcca7aab7..c8e0d3b7f5 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -34,15 +34,60 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + UTF-8 1.8 diff --git a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java index 32be4c6a0a..94309cf1a6 100644 --- a/spring-mockito/src/main/java/com/baeldung/MocksApplication.java +++ b/spring-mockito/src/main/java/com/baeldung/MocksApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MocksApplication { - public static void main(String[] args) { - SpringApplication.run(MocksApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MocksApplication.class, args); + } } diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java index 631a8634be..70861a96e1 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MocksApplication.class) -public class UserServiceTest { +public class UserServiceIntegrationTest { @Autowired private UserService userService; diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 951d80033e..996a7d96b1 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -10,3 +10,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) +- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp) +- [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) +- [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) +- [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 7361d16b33..011de70ad2 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -6,6 +6,7 @@ 0.1-SNAPSHOT spring-mvc-java war + @@ -34,16 +35,12 @@ spring-messaging ${org.springframework.version} + - - com.fasterxml.jackson.core - jackson-core - 2.7.3 - com.fasterxml.jackson.core jackson-databind - 2.7.3 + ${jackson.version} @@ -59,6 +56,7 @@ 1.2 runtime + org.springframework @@ -82,6 +80,11 @@ commons-fileupload 1.3.1 + + net.sourceforge.htmlunit + htmlunit + ${net.sourceforge.htmlunit} + @@ -95,18 +98,6 @@ ${thymeleaf.version} - - - com.fasterxml.jackson.core - jackson-core - 2.1.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.1.2 - - org.slf4j @@ -210,52 +201,73 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - jetty8x - embedded - - - - - - - 8082 - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.2.5.RELEASE 4.0.4.RELEASE 2.1.4.RELEASE + 2.7.8 + 4.3.11.Final 5.1.38 + 1.7.21 1.1.5 5.2.2.Final + 19.0 3.4 + 1.3 4.12 @@ -264,6 +276,7 @@ 4.5 2.9.0 2.23 + 3.5.1 2.6 diff --git a/spring-mvc-java/src/main/README.md b/spring-mvc-java/src/main/README.md new file mode 100644 index 0000000000..20ee1918af --- /dev/null +++ b/spring-mvc-java/src/main/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA b/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA rename to spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB b/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB rename to spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java index c1f7f52215..76d53e132a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java @@ -2,14 +2,14 @@ package com.baeldung.model; public class Message { - private String from; - private String text; + private String from; + private String text; - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java index fc201ed016..9aad564b1e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java @@ -2,26 +2,26 @@ package com.baeldung.model; public class OutputMessage { - private String from; - private String text; - private String time; + private String from; + private String text; + private String time; - public OutputMessage(final String from, final String text, final String time) { + public OutputMessage(final String from, final String text, final String time) { - this.from = from; - this.text = text; - this.time = time; - } + this.from = from; + this.text = text; + this.time = time; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public String getTime() { - return time; - } + public String getTime() { + return time; + } - public String getFrom() { - return from; - } + public String getFrom() { + return from; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java index f428fc3223..80ce22edd6 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -1,17 +1,16 @@ package com.baeldung.spring.web.config; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import java.util.Set; + public class MainWebAppInitializer implements WebApplicationInitializer { private static final String TMP_FOLDER = "/tmp"; @@ -28,7 +27,6 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("com.baeldung.spring.web.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); // Handles requests into the application diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java index 6330041c60..5f3eb1312d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -10,15 +10,15 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { - @Override - public void configureMessageBroker(final MessageBrokerRegistry config) { - config.enableSimpleBroker("/topic"); - config.setApplicationDestinationPrefixes("/app"); - } + @Override + public void configureMessageBroker(final MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } - @Override - public void registerStompEndpoints(final StompEndpointRegistry registry) { - registry.addEndpoint("/chat").withSockJS(); - } + @Override + public void registerStompEndpoints(final StompEndpointRegistry registry) { + registry.addEndpoint("/chat").withSockJS(); + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java index 8dcfe68a84..e92abfdc47 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/CompanyController.java @@ -22,59 +22,55 @@ import com.baeldung.model.Company; @Controller public class CompanyController { - Map companyMap = new HashMap<>(); + Map companyMap = new HashMap<>(); - @RequestMapping(value = "/company", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("companyHome", "company", new Company()); - } + @RequestMapping(value = "/company", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("companyHome", "company", new Company()); + } - @RequestMapping(value = "/company/{Id}", produces = { "application/json", - "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Company getCompanyById(@PathVariable final long Id) { - return companyMap.get(Id); - } + @RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Company getCompanyById(@PathVariable final long Id) { + return companyMap.get(Id); + } - @RequestMapping(value = "/addCompany", method = RequestMethod.POST) - public String submit(@ModelAttribute("company") final Company company, - final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", company.getName()); - model.addAttribute("id", company.getId()); + @RequestMapping(value = "/addCompany", method = RequestMethod.POST) + public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", company.getName()); + model.addAttribute("id", company.getId()); - companyMap.put(company.getId(), company); + companyMap.put(company.getId(), company); - return "companyView"; - } + return "companyView"; + } - @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getEmployeeDataFromCompany( - @MatrixVariable(pathVar = "employee") final Map matrixVars) { - return new ResponseEntity<>(matrixVars, HttpStatus.OK); - } + @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map matrixVars) { + return new ResponseEntity<>(matrixVars, HttpStatus.OK); + } - @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) - @ResponseBody - public ResponseEntity> getCompanyName( - @MatrixVariable(value = "name", pathVar = "company") final String name) { - final Map result = new HashMap(); - result.put("name", name); - return new ResponseEntity<>(result, HttpStatus.OK); - } + @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) { + final Map result = new HashMap(); + result.put("name", name); + return new ResponseEntity<>(result, HttpStatus.OK); + } - @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - public Company getCompanyResponseBody() { - final Company company = new Company(2, "ABC"); - return company; - } + @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public Company getCompanyResponseBody() { + final Company company = new Company(2, "ABC"); + return company; + } - @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCompanyResponseEntity() { - final Company company = new Company(3, "123"); - return new ResponseEntity(company, HttpStatus.OK); - } + @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getCompanyResponseEntity() { + final Company company = new Company(3, "123"); + return new ResponseEntity(company, HttpStatus.OK); + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index fd5fa6bc27..ef76059567 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -31,10 +31,8 @@ public class EmployeeController { return new ModelAndView("employeeHome", "employee", new Employee()); } - @RequestMapping(value = "/employee/{Id}", produces = {"application/json", "application/xml"}, method = RequestMethod.GET) - public - @ResponseBody - Employee getEmployeeById(@PathVariable final long Id) { + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java index cfc73aeabe..111bf023f7 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java @@ -10,15 +10,15 @@ import org.springframework.web.bind.annotation.RequestParam; @RequestMapping("/message") public class MessageController { - @RequestMapping(value = "/showForm", method = RequestMethod.GET) - public String showForm() { - return "message"; - } + @RequestMapping(value = "/showForm", method = RequestMethod.GET) + public String showForm() { + return "message"; + } - @RequestMapping(value = "/processForm", method = RequestMethod.POST) - public String processForm(@RequestParam("message") final String message, final Model model) { - model.addAttribute("message", message); - return "message"; - } + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@RequestParam("message") final String message, final Model model) { + model.addAttribute("message", message); + return "message"; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java index 8557b15492..7b2c6870df 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-mvc-java/src/test/README.md b/spring-mvc-java/src/test/README.md new file mode 100644 index 0000000000..20ee1918af --- /dev/null +++ b/spring-mvc-java/src/test/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java similarity index 98% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java index 19bf4d0fac..0837100bfa 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingIntegrationTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopLoggingTest { +public class AopLoggingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java index 4ad5a3e1a6..c9ab2fb4bb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPerformanceTest { +public class AopPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java index c075db9fc6..cf9c83a93d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingIntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) -public class AopPublishingTest { +public class AopPublishingIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java index 4d2df50d18..3b380315e8 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceIntegrationTest.java @@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/com/baeldung/aop/beans.xml") -public class AopXmlConfigPerformanceTest { +public class AopXmlConfigPerformanceIntegrationTest { @Before public void setUp() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java new file mode 100644 index 0000000000..42847f4dd1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.circulardependency; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class }) +public class CircularDependencyIntegrationTest { + + @Autowired + ApplicationContext context; + + @Bean + public CircularDependencyA getCircularDependencyA() { + return new CircularDependencyA(); + } + + @Bean + public CircularDependencyB getCircularDependencyB() { + return new CircularDependencyB(); + } + + @Test + public void givenCircularDependency_whenSetterInjection_thenItWorks() { + final CircularDependencyA circA = context.getBean(CircularDependencyA.class); + + Assert.assertEquals("Hi!", circA.getCircB().getMessage()); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest deleted file mode 100644 index 4229f21f10..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyTest +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.circulardependency; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }) -public class CircularDependencyTest { - - @Autowired - ApplicationContext context; - - @Bean - public CircularDependencyA getCircularDependencyA() { - return new CircularDependencyA(); - } - - @Bean - public CircularDependencyB getCircularDependencyB() { - return new CircularDependencyB(); - } - - @Test - public void givenCircularDependency_whenSetterInjection_thenItWorks() { - final CircularDependencyA circA = context.getBean(CircularDependencyA.class); - - Assert.assertEquals("Hi!", circA.getCircB().getMessage()); - } -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig b/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig rename to spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java deleted file mode 100644 index 58e5f9829b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.htmlunit; - -import org.junit.Assert; -import org.junit.Test; - -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - -public class HtmlUnitAndJUnitTest { - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient webClient = new WebClient()) { - - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java new file mode 100644 index 0000000000..406975b6cc --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; +import java.net.MalformedURLException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); + } + + // + + @Test + @Ignore("Related view message.html does not exist check MessageController") + public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { + final String text = "Hello world!"; + final HtmlPage page = webClient.getPage("http://localhost/message/showForm"); + System.out.println(page.asXml()); + + final HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + final HtmlForm form = page.getForms().get(0); + final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); + final HtmlPage newPage = submit.click(); + + final String receivedText = newPage.getHtmlElementById("received").getTextContent(); + + Assert.assertEquals(receivedText, text); + System.out.println(newPage.asXml()); + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient client = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java deleted file mode 100644 index dcc7555ae2..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.htmlunit; - -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; -import org.springframework.web.context.WebApplicationContext; - -import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlForm; -import com.gargoylesoftware.htmlunit.html.HtmlPage; -import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; -import com.gargoylesoftware.htmlunit.html.HtmlTextInput; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { TestConfig.class }) -public class HtmlUnitAndSpringTest { - - @Autowired - private WebApplicationContext wac; - - private WebClient webClient; - - @Before - public void setup() { - webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); - } - - @Test - @Ignore - public void givenAMessage_whenSent_thenItShows() { - final String text = "Hello world!"; - HtmlPage page; - - try { - - page = webClient.getPage("http://localhost/message/showForm"); - System.out.println(page.asXml()); - - final HtmlTextInput messageText = page.getHtmlElementById("message"); - messageText.setValueAttribute(text); - - final HtmlForm form = page.getForms().get(0); - final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); - final HtmlPage newPage = submit.click(); - - final String receivedText = newPage.getHtmlElementById("received").getTextContent(); - - Assert.assertEquals(receivedText, text); - System.out.println(newPage.asXml()); - - } catch (FailingHttpStatusCodeException | IOException e) { - e.printStackTrace(); - } - - } - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient client = new WebClient()) { - - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java new file mode 100644 index 0000000000..6a7e961eb1 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitTest { + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient webClient = new WebClient()) { + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java index 16d18717e6..9919d7571d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -10,31 +10,31 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScraping { - public static void main(final String[] args) throws Exception { - try (final WebClient webClient = new WebClient()) { + public static void main(final String[] args) throws Exception { + try (final WebClient webClient = new WebClient()) { - webClient.getOptions().setCssEnabled(false); - webClient.getOptions().setJavaScriptEnabled(false); + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); - final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); - final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); + final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); - System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + System.out.println("Entering: " + latestPostLink.getHrefAttribute()); - final HtmlPage postPage = latestPostLink.click(); + final HtmlPage postPage = latestPostLink.click(); - final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); - System.out.println("Title: " + heading1.getTextContent()); + final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); + System.out.println("Title: " + heading1.getTextContent()); - final List headings2 = (List) postPage.getByXPath("//h2"); + final List headings2 = (List) postPage.getByXPath("//h2"); - final StringBuilder sb = new StringBuilder(heading1.getTextContent()); - for (final HtmlHeading2 h2 : headings2) { - sb.append("\n").append(h2.getTextContent()); - } + final StringBuilder sb = new StringBuilder(heading1.getTextContent()); + for (final HtmlHeading2 h2 : headings2) { + sb.append("\n").append(h2.getTextContent()); + } - System.out.println(sb.toString()); - } - } + System.out.println(sb.toString()); + } + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 1357310b1f..17a68d67a5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -15,28 +15,28 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class TestConfig extends WebMvcConfigurerAdapter { - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } - @Bean - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } + @Bean + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } - @Bean - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - return templateEngine; - } + @Bean + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java index c1e79a2a63..86420a5fbd 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeMvcIntegrationTest.java @@ -23,7 +23,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTest { +public class EmployeeMvcIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java similarity index 97% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java index 19806e0559..e84c20c973 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeNoMvcIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.web.controller; -import org.junit.Before; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -15,7 +15,7 @@ import com.baeldung.spring.web.config.WebConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) -public class EmployeeTestWithoutMockMvc { +public class EmployeeNoMvcIntegrationTest { @Autowired private EmployeeController employeeController; @@ -25,9 +25,10 @@ public class EmployeeTestWithoutMockMvc { employeeController.initEmployees(); } + // + @Test public void whenInitEmployees_thenVerifyValuesInitiation() { - Employee employee1 = employeeController.employeeMap.get(1L); Employee employee2 = employeeController.employeeMap.get(2L); Employee employee3 = employeeController.employeeMap.get(3L); diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java index d1d1167369..db984eadfb 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.web.controller; - import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import javax.servlet.ServletContext; @@ -25,7 +24,7 @@ import com.baeldung.spring.web.config.ApplicationConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = {ApplicationConfig.class}) +@ContextConfiguration(classes = { ApplicationConfig.class }) public class GreetControllerIntegrationTest { @Autowired @@ -35,7 +34,6 @@ public class GreetControllerIntegrationTest { private static final String CONTENT_TYPE = "application/json"; - @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); @@ -74,8 +72,8 @@ public class GreetControllerIntegrationTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); } @Test diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java similarity index 77% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java index 0fd71a46dd..eacd256438 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/GreetControllerUnitTest.java @@ -1,17 +1,19 @@ package com.baeldung.web.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -public class GreetControllerTest { +public class GreetControllerUnitTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json"; @@ -43,19 +45,17 @@ public class GreetControllerTest { @Test public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); + this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")); } @Test public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) - .andExpect(jsonPath("$.message").value("Hello World!!!")); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!")); } @Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) - .andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); + this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) + .andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md b/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md new file mode 100644 index 0000000000..9923962dde --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration) diff --git a/spring-mvc-velocity/README.md b/spring-mvc-velocity/README.md new file mode 100644 index 0000000000..401e135f75 --- /dev/null +++ b/spring-mvc-velocity/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Quick Guide to Spring MVC with Velocity](http://www.baeldung.com/spring-mvc-with-velocity) diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 6c63e0be18..83f3150df9 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -139,7 +139,7 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java @@ -151,6 +151,41 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.1.4.RELEASE diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java index 679a455f3f..10b54e345c 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/controller/MainController.java @@ -17,13 +17,12 @@ public class MainController { @Autowired private ITutorialsService tutService; - @RequestMapping(value ="/", method = RequestMethod.GET) + @RequestMapping(value = "/", method = RequestMethod.GET) public String welcomePage() { - return "index"; + return "index"; } - - - @RequestMapping(value ="/list", method = RequestMethod.GET) + + @RequestMapping(value = "/list", method = RequestMethod.GET) public String listTutorialsPage(Model model) { List list = tutService.listTutorials(); model.addAttribute("tutorials", list); @@ -37,6 +36,5 @@ public class MainController { public void setTutService(ITutorialsService tutService) { this.tutService = tutService; } - - + } \ No newline at end of file diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java index 24059f2662..237b603590 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/ITutorialsService.java @@ -6,5 +6,5 @@ import java.util.List; public interface ITutorialsService { - List listTutorials(); + List listTutorials(); } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java index f67cc0824f..9d48e130c8 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/service/TutorialsService.java @@ -10,9 +10,6 @@ import java.util.List; public class TutorialsService implements ITutorialsService { public List listTutorials() { - return Arrays.asList( - new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), - new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor") - ); + return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")); } } diff --git a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java index ce8ce1919a..17388b52b0 100644 --- a/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java +++ b/spring-mvc-velocity/src/main/java/com/baeldung/mvc/velocity/spring/config/WebConfig.java @@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"}) +@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" }) public class WebConfig extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java similarity index 95% rename from spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java rename to spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java index a9fb242755..7f92e1ee45 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerTest.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/DataContentControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.mvc.velocity.test.config.TestConfig; // @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"}) @ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration -public class DataContentControllerTest { +public class DataContentControllerIntegrationTest { private MockMvc mockMvc; @@ -38,7 +38,6 @@ public class DataContentControllerTest { @Before public void setUp() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @@ -53,9 +52,9 @@ public class DataContentControllerTest { mockMvc.perform(get("/list")).andExpect(xpath("//table").exists()); mockMvc.perform(get("/list")).andExpect(xpath("//td[@id='tutId_1']").exists()); } - + @Test - public void whenCallingIndex_thenViewOK() throws Exception{ + public void whenCallingIndex_thenViewOK() throws Exception { mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0)); } } diff --git a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java index 8b84bcdd23..a75cd1291a 100644 --- a/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java +++ b/spring-mvc-velocity/src/test/java/com/baeldung/mvc/velocity/test/config/TestConfig.java @@ -8,7 +8,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver; @Configuration public class TestConfig { - @Bean public ViewResolver viewResolver() { @@ -19,14 +18,12 @@ public class TestConfig { bean.setSuffix(".vm"); return bean; } - + @Bean public VelocityConfigurer velocityConfig() { VelocityConfigurer velocityConfigurer = new VelocityConfigurer(); velocityConfigurer.setResourceLoaderPath("/"); return velocityConfigurer; } - - } diff --git a/spring-mvc-web-vs-initializer/README.MD b/spring-mvc-web-vs-initializer/README.MD index 8b13789179..4759cf6137 100644 --- a/spring-mvc-web-vs-initializer/README.MD +++ b/spring-mvc-web-vs-initializer/README.MD @@ -1 +1,2 @@ - +### Relevant Articles: +- [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) diff --git a/spring-mvc-web-vs-initializer/pom.xml b/spring-mvc-web-vs-initializer/pom.xml index 0d735e7188..b448673ef8 100644 --- a/spring-mvc-web-vs-initializer/pom.xml +++ b/spring-mvc-web-vs-initializer/pom.xml @@ -146,17 +146,64 @@ - - spring-mvc-web-vs-initializer - - - src/main/resources - true - - - - + + spring-mvc-web-vs-initializer + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.3.1.RELEASE diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java similarity index 97% rename from spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java rename to spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java index 99b5ef8c2f..0461cc8fcc 100644 --- a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletTest.java +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/JavaServletIntegrationTest.java @@ -20,7 +20,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(loader=AnnotationConfigWebContextLoader.class, classes = MvcConfig.class) -public class JavaServletTest { +public class JavaServletIntegrationTest { private MockMvc mockMvc; diff --git a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java similarity index 97% rename from spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java rename to spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java index e7695e36c0..e1273f8f88 100644 --- a/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletTest.java +++ b/spring-mvc-web-vs-initializer/src/test/java/org/baeldung/controller/XmlServletIntegrationTest.java @@ -19,7 +19,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(loader=GenericXmlWebContextLoader.class, locations = "classpath*:mvc-configuration.xml") -public class XmlServletTest { +public class XmlServletIntegrationTest { private MockMvc mockMvc; diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index ce823a9682..783bbb2ef4 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) +- [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 9c65ccdadd..849699cfae 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung 0.1-SNAPSHOT @@ -99,16 +100,11 @@ - - com.fasterxml.jackson.core - jackson-core - 2.7.2 - - - com.fasterxml.jackson.core - jackson-databind - 2.7.2 - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + @@ -165,6 +161,7 @@ 4.2.5.RELEASE + 2.7.8 1.7.13 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 76351b96f7..b5238b04d5 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java index bee09b742a..f299c46dbc 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - @Bean - public MessageSource messageSource() { + @Bean + public MessageSource messageSource() { - final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); - ms.setBasenames("messages"); - return ms; - } + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - @Bean - public ResourceBundle getBeanResourceBundle() { + @Bean + public ResourceBundle getBeanResourceBundle() { - final Locale locale = Locale.getDefault(); - return new MessageSourceResourceBundle(messageSource(), locale); - } + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); - return bean; - } + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index aa25f47a2a..fa76933f8f 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee; @Controller public class EmployeeController { - Map employeeMap = new HashMap<>(); + Map employeeMap = new HashMap<>(); - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } - @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - employeeMap.put(employee.getId(), employee); - return "employeeView"; - } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index cc9d66d4d4..17f0801a6e 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -11,8 +11,7 @@ public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java index 614888ae42..c7f3adb594 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using ControllerClassNameHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using ControllerClassNameHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java index 6ed3d06ab7..a0be507125 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using BeanNameUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using BeanNameUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java index 39dabf86ed..71d9ad7845 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/PersonController.java @@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PersonController { - @Autowired - PersonValidator validator; + @Autowired + PersonValidator validator; - @RequestMapping(value = "/person", method = RequestMethod.GET) - public ModelAndView showForm(final Model model) { + @RequestMapping(value = "/person", method = RequestMethod.GET) + public ModelAndView showForm(final Model model) { - initData(model); - return new ModelAndView("personForm", "person", new Person()); - } + initData(model); + return new ModelAndView("personForm", "person", new Person()); + } - @RequestMapping(value = "/addPerson", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, - final ModelMap modelMap, final Model model) { + @RequestMapping(value = "/addPerson", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) { - validator.validate(person, result); + validator.validate(person, result); - if (result.hasErrors()) { + if (result.hasErrors()) { - initData(model); - return "personForm"; - } + initData(model); + return "personForm"; + } - modelMap.addAttribute("person", person); + modelMap.addAttribute("person", person); - return "personView"; - } + return "personView"; + } - private void initData(final Model model) { + private void initData(final Model model) { - final List favouriteLanguageItem = new ArrayList(); - favouriteLanguageItem.add("Java"); - favouriteLanguageItem.add("C++"); - favouriteLanguageItem.add("Perl"); - model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); + final List favouriteLanguageItem = new ArrayList(); + favouriteLanguageItem.add("Java"); + favouriteLanguageItem.add("C++"); + favouriteLanguageItem.add("Perl"); + model.addAttribute("favouriteLanguageItem", favouriteLanguageItem); - final List jobItem = new ArrayList(); - jobItem.add("Full time"); - jobItem.add("Part time"); - model.addAttribute("jobItem", jobItem); + final List jobItem = new ArrayList(); + jobItem.add("Full time"); + jobItem.add("Part time"); + model.addAttribute("jobItem", jobItem); - final Map countryItems = new LinkedHashMap(); - countryItems.put("US", "United Stated"); - countryItems.put("IT", "Italy"); - countryItems.put("UK", "United Kingdom"); - countryItems.put("FR", "Grance"); - model.addAttribute("countryItems", countryItems); + final Map countryItems = new LinkedHashMap(); + countryItems.put("US", "United Stated"); + countryItems.put("IT", "Italy"); + countryItems.put("UK", "United Kingdom"); + countryItems.put("FR", "Grance"); + model.addAttribute("countryItems", countryItems); - final List fruit = new ArrayList(); - fruit.add("Banana"); - fruit.add("Mango"); - fruit.add("Apple"); - model.addAttribute("fruit", fruit); + final List fruit = new ArrayList(); + fruit.add("Banana"); + fruit.add("Mango"); + fruit.add("Apple"); + model.addAttribute("fruit", fruit); - final List books = new ArrayList(); - books.add("The Great Gatsby"); - books.add("Nineteen Eighty-Four"); - books.add("The Lord of the Rings"); - model.addAttribute("books", books); - } + final List books = new ArrayList(); + books.add("The Great Gatsby"); + books.add("Nineteen Eighty-Four"); + books.add("The Lord of the Rings"); + model.addAttribute("books", books); + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java index 5459481674..2760fb8f89 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -11,8 +11,7 @@ public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); - model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + - " using SimpleUrlHandlerMapping."); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java index 88e4f9ff4c..01638fbe76 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/form/Person.java @@ -7,146 +7,146 @@ import org.springframework.web.multipart.MultipartFile; public class Person { - private long id; + private long id; - private String name; - private String email; - private String dateOfBirth; + private String name; + private String email; + private String dateOfBirth; - @NotEmpty - private String password; - private String sex; - private String country; - private String book; - private String job; - private boolean receiveNewsletter; - private String[] hobbies; - private List favouriteLanguage; - private List fruit; - private String notes; - private MultipartFile file; + @NotEmpty + private String password; + private String sex; + private String country; + private String book; + private String job; + private boolean receiveNewsletter; + private String[] hobbies; + private List favouriteLanguage; + private List fruit; + private String notes; + private MultipartFile file; - public Person() { - super(); - } + public Person() { + super(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(final String email) { - this.email = email; - } + public void setEmail(final String email) { + this.email = email; + } - public String getDateOfBirth() { - return dateOfBirth; - } + public String getDateOfBirth() { + return dateOfBirth; + } - public void setDateOfBirth(final String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } + public void setDateOfBirth(final String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(final String password) { - this.password = password; - } + public void setPassword(final String password) { + this.password = password; + } - public String getSex() { - return sex; - } + public String getSex() { + return sex; + } - public void setSex(final String sex) { - this.sex = sex; - } + public void setSex(final String sex) { + this.sex = sex; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(final String country) { - this.country = country; - } + public void setCountry(final String country) { + this.country = country; + } - public String getJob() { - return job; - } + public String getJob() { + return job; + } - public void setJob(final String job) { - this.job = job; - } + public void setJob(final String job) { + this.job = job; + } - public boolean isReceiveNewsletter() { - return receiveNewsletter; - } + public boolean isReceiveNewsletter() { + return receiveNewsletter; + } - public void setReceiveNewsletter(final boolean receiveNewsletter) { - this.receiveNewsletter = receiveNewsletter; - } + public void setReceiveNewsletter(final boolean receiveNewsletter) { + this.receiveNewsletter = receiveNewsletter; + } - public String[] getHobbies() { - return hobbies; - } + public String[] getHobbies() { + return hobbies; + } - public void setHobbies(final String[] hobbies) { - this.hobbies = hobbies; - } + public void setHobbies(final String[] hobbies) { + this.hobbies = hobbies; + } - public List getFavouriteLanguage() { - return favouriteLanguage; - } + public List getFavouriteLanguage() { + return favouriteLanguage; + } - public void setFavouriteLanguage(final List favouriteLanguage) { - this.favouriteLanguage = favouriteLanguage; - } + public void setFavouriteLanguage(final List favouriteLanguage) { + this.favouriteLanguage = favouriteLanguage; + } - public String getNotes() { - return notes; - } + public String getNotes() { + return notes; + } - public void setNotes(final String notes) { - this.notes = notes; - } + public void setNotes(final String notes) { + this.notes = notes; + } - public List getFruit() { - return fruit; - } + public List getFruit() { + return fruit; + } - public void setFruit(final List fruit) { - this.fruit = fruit; - } + public void setFruit(final List fruit) { + this.fruit = fruit; + } - public String getBook() { - return book; - } + public String getBook() { + return book; + } - public void setBook(final String book) { - this.book = book; - } + public void setBook(final String book) { + this.book = book; + } - public MultipartFile getFile() { - return file; - } + public MultipartFile getFile() { + return file; + } - public void setFile(final MultipartFile file) { - this.file = file; - } + public void setFile(final MultipartFile file) { + this.file = file; + } } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java index 3a271f6545..f7625bacd9 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/validator/PersonValidator.java @@ -9,14 +9,14 @@ import org.springframework.validation.Validator; @Component public class PersonValidator implements Validator { - @Override - public boolean supports(final Class calzz) { - return Person.class.isAssignableFrom(calzz); - } + @Override + public boolean supports(final Class calzz) { + return Person.class.isAssignableFrom(calzz); + } - @Override - public void validate(final Object obj, final Errors errors) { + @Override + public void validate(final Object obj, final Errors errors) { - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); - } + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name"); + } } \ No newline at end of file diff --git a/spring-protobuf/README.md b/spring-protobuf/README.md new file mode 100644 index 0000000000..dad0e3f54a --- /dev/null +++ b/spring-protobuf/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring REST API with Protocol Buffers](http://www.baeldung.com/spring-rest-api-with-protocol-buffers) diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 1275d72edf..a080d51221 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -37,7 +37,6 @@ org.apache.httpcomponents httpclient - 4.5.2
@@ -47,12 +46,57 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 1.8 1.8 + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java similarity index 98% rename from spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java rename to spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index a17082cea7..914cf18627 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest -public class ApplicationTest { +public class ApplicationIntegrationTest { private static final String COURSE1_URL = "http://localhost:8080/courses/1"; diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java index e51e4ad43d..547ef78d84 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/SpringQuartzApp.java @@ -10,7 +10,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; public class SpringQuartzApp { public static void main(String[] args) { - new SpringApplicationBuilder(SpringQuartzApp.class) - .showBanner(false).run(args); + new SpringApplicationBuilder(SpringQuartzApp.class).showBanner(false).run(args); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index a944f8fe43..6601df6c94 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -45,8 +45,7 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) - throws SchedulerException, IOException { + public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); @@ -64,9 +63,7 @@ public class QrtzScheduler { @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class).storeDurably() - .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) - .withDescription("Invoke Sample Job service...").build(); + return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean @@ -75,10 +72,6 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) - .withDescription("Sample trigger") - .withSchedule( - simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) - .build(); + return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 9474272a3c..7c50f9a231 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -19,8 +19,7 @@ public class SampleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { - logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), - context.getFireTime()); + logger.info("Job ** {} ** fired @ {}", context.getJobDetail().getKey().getName(), context.getFireTime()); jobService.executeSampleJob(); diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java index 0e24238467..d3034ae7af 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/config/AutoWiringSpringBeanJobFactory.java @@ -11,21 +11,17 @@ import org.springframework.scheduling.quartz.SpringBeanJobFactory; * Adds auto-wiring support to quartz jobs. * @see "https://gist.github.com/jelies/5085593" */ -public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory - implements ApplicationContextAware { +public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; - - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { beanFactory = applicationContext.getAutowireCapableBeanFactory(); } @Override - protected Object createJobInstance(final TriggerFiredBundle bundle) - throws Exception { + protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 331c9a644c..ce496df742 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -1,74 +1,76 @@ - - 4.0.0 - spring-rest-angular - spring-rest-angular - com.baeldung - 1.0 - war - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.data - spring-data-commons - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - - - org.springframework - spring-test - test - - - org.apache.commons - commons-lang3 - 3.3 - - - com.google.guava - guava - 19.0 - - - junit - junit - test - - - io.rest-assured - rest-assured - 3.0.0 - test - - - io.rest-assured - spring-mock-mvc - 3.0.0 - test - - + + 4.0.0 + spring-rest-angular + spring-rest-angular + com.baeldung + 1.0 + war + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + + + org.springframework + spring-test + test + + + org.apache.commons + commons-lang3 + 3.3 + + + com.google.guava + guava + ${guava.version} + + + junit + junit + test + + + io.rest-assured + rest-assured + 3.0.0 + test + + + io.rest-assured + spring-mock-mvc + 3.0.0 + test + + + angular-spring-rest-sample @@ -90,6 +92,56 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 19.0 + + diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java similarity index 98% rename from spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java rename to spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 1199f15ab3..6ad80e5caf 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.core.IsEqual.*; @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:8888") -public class StudentServiceTest { +public class StudentServiceIntegrationTest { private static final String ENDPOINT = "http://localhost:8888/student/get"; diff --git a/spring-rest-docs/README.MD b/spring-rest-docs/README.MD index 2a87b46021..f5d001d126 100644 --- a/spring-rest-docs/README.MD +++ b/spring-rest-docs/README.MD @@ -1,2 +1,5 @@ ###The Course The "REST With Spring" Classes: http://bit.ly/restwithspring + +###Relevant Articles: +- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) diff --git a/spring-rest/README.md b/spring-rest/README.md index 7d993b38b8..671fa4996b 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -1,12 +1,12 @@ -========= - ## Spring REST Example Project ###The Course The "REST With Spring" Classes: http://bit.ly/restwithspring -### Relevant Articles: +### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) - [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) +- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) +- [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 18cb1dc72a..69ab4ed361 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -15,7 +15,7 @@ - + org.springframework.boot spring-boot-starter-thymeleaf @@ -71,7 +71,7 @@ com.fasterxml.jackson.core jackson-databind - + com.fasterxml.jackson.dataformat jackson-dataformat-xml @@ -118,6 +118,14 @@ log4j-over-slf4j + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + @@ -153,14 +161,14 @@ rest-assured ${rest-assured.version} - + com.google.protobuf protobuf-java 2.6.1 - + com.esotericsoftware kryo @@ -198,7 +206,7 @@ maven-surefire-plugin - **/*LiveTest.java + **/*LiveTest.java @@ -285,7 +293,7 @@ - + @@ -320,6 +328,9 @@ 2.19.1 1.6.0 + + 3.4.1 + diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java index d640ac671d..aa694c08ed 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java @@ -8,9 +8,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class CompanyController { - @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) - public Company getCompanyRest() { - final Company company = new Company(1, "Xpto"); - return company; - } + @RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE) + public Company getCompanyRest() { + final Company company = new Company(1, "Xpto"); + return company; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java index f3e3738bfe..1cc3eae432 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java @@ -14,26 +14,26 @@ import com.fasterxml.jackson.annotation.JsonView; @RestController public class ItemController { - @JsonView(Views.Public.class) - @RequestMapping("/items/{id}") - public Item getItemPublic(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Public.class) + @RequestMapping("/items/{id}") + public Item getItemPublic(@PathVariable final int id) { + return ItemManager.getById(id); + } - @JsonView(Views.Internal.class) - @RequestMapping("/items/internal/{id}") - public Item getItemInternal(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Internal.class) + @RequestMapping("/items/internal/{id}") + public Item getItemInternal(@PathVariable final int id) { + return ItemManager.getById(id); + } - @RequestMapping("/date") - public Date getCurrentDate() throws Exception { - return new Date(); - } + @RequestMapping("/date") + public Date getCurrentDate() throws Exception { + return new Date(); + } - @RequestMapping("/delay/{seconds}") - public void getCurrentTime(@PathVariable final int seconds) throws Exception { + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { - Thread.sleep(seconds * 1000); - } + Thread.sleep(seconds * 1000); + } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java index 7d62cc0c66..996f229128 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java @@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon @ControllerAdvice public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - public JsonpControllerAdvice() { - super("callback"); - } + public JsonpControllerAdvice() { + super("callback"); + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java index 348ee6d596..458bdaf170 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java @@ -3,8 +3,8 @@ package org.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message") +@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message") public class ForbiddenException extends RuntimeException { - private static final long serialVersionUID = 6826605655586311552L; + private static final long serialVersionUID = 6826605655586311552L; } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java index c7d0718140..3164d604ad 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Company.java @@ -2,37 +2,37 @@ package org.baeldung.web.dto; public class Company { - private long id; - private String name; + private long id; + private String name; - public Company() { - super(); - } + public Company() { + super(); + } - public Company(final long id, final String name) { - this.id = id; - this.name = name; - } + public Company(final long id, final String name) { + this.id = id; + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - @Override - public String toString() { - return "Company [id=" + id + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Company [id=" + id + ", name=" + name + "]"; + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java index 61251ea33a..8ca96c38fc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java @@ -4,617 +4,594 @@ package org.baeldung.web.dto; public final class FooProtos { - private FooProtos() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface FooOrBuilder extends - // @@protoc_insertion_point(interface_extends:baeldung.Foo) - com.google.protobuf.MessageOrBuilder { - - /** - * required int64 id = 1; - */ - boolean hasId(); - /** - * required int64 id = 1; - */ - long getId(); - - /** - * required string name = 2; - */ - boolean hasName(); - /** - * required string name = 2; - */ - java.lang.String getName(); - /** - * required string name = 2; - */ - com.google.protobuf.ByteString - getNameBytes(); - } - /** - * Protobuf type {@code baeldung.Foo} - */ - public static final class Foo extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:baeldung.Foo) - FooOrBuilder { - // Use Foo.newBuilder() to construct. - private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final Foo defaultInstance; - public static Foo getDefaultInstance() { - return defaultInstance; + private FooProtos() { } - public Foo getDefaultInstanceForType() { - return defaultInstance; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { } - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Foo( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - bitField0_ |= 0x00000001; - id_ = input.readInt64(); - break; - } - case 18: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000002; - name_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + public interface FooOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Foo) + com.google.protobuf.MessageOrBuilder { + + /** + * required int64 id = 1; + */ + boolean hasId(); + + /** + * required int64 id = 1; + */ + long getId(); + + /** + * required string name = 2; + */ + boolean hasName(); + + /** + * required string name = 2; + */ + java.lang.String getName(); + + /** + * required string name = 2; + */ + com.google.protobuf.ByteString getNameBytes(); } - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public Foo parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Foo(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int ID_FIELD_NUMBER = 1; - private long id_; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - - public static final int NAME_FIELD_NUMBER = 2; - private java.lang.Object name_; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private void initFields() { - id_ = 0L; - name_ = ""; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (!hasId()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasName()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeInt64(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeBytes(2, getNameBytes()); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(1, id_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getNameBytes()); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } /** * Protobuf type {@code baeldung.Foo} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); - } - - // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + public static final class Foo extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Foo) + FooOrBuilder { + // Use Foo.newBuilder() to construct. + private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); } - } - private static Builder create() { - return new Builder(); - } - public Builder clear() { - super.clear(); - id_ = 0L; - bitField0_ = (bitField0_ & ~0x00000001); - name_ = ""; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; - } - - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); - } - - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private Foo(boolean noInit) { + this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - return result; - } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + private static final Foo defaultInstance; + + public static Foo getDefaultInstance() { + return defaultInstance; } - result.id_ = id_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; + + public Foo getDefaultInstanceForType() { + return defaultInstance; } - result.name_ = name_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other); - } else { - super.mergeFrom(other); - return this; + private final com.google.protobuf.UnknownFieldSet unknownFields; + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; - if (other.hasId()) { - setId(other.getId()); + private Foo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + id_ = input.readInt64(); + break; + } + case 18: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000002; + name_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - if (other.hasName()) { - bitField0_ |= 0x00000002; - name_ = other.name_; - onChanged(); + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - public final boolean isInitialized() { - if (!hasId()) { - - return false; + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); } - if (!hasName()) { - - return false; - } - return true; - } - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private long id_ ; - /** - * required int64 id = 1; - */ - public boolean hasId() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required int64 id = 1; - */ - public long getId() { - return id_; - } - /** - * required int64 id = 1; - */ - public Builder setId(long value) { - bitField0_ |= 0x00000001; - id_ = value; - onChanged(); - return this; - } - /** - * required int64 id = 1; - */ - public Builder clearId() { - bitField0_ = (bitField0_ & ~0x00000001); - id_ = 0L; - onChanged(); - return this; - } - - private java.lang.Object name_ = ""; - /** - * required string name = 2; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string name = 2; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * required string name = 2; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * required string name = 2; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000002); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * required string name = 2; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - name_ = value; - onChanged(); - return this; - } - - // @@protoc_insertion_point(builder_scope:baeldung.Foo) - } - - static { - defaultInstance = new Foo(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:baeldung.Foo) - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_baeldung_Foo_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_baeldung_Foo_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + - "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + - ".dtoB\tFooProtos" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } + public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Foo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Foo(input, extensionRegistry); + } }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_baeldung_Foo_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_baeldung_Foo_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_baeldung_Foo_descriptor, - new java.lang.String[] { "Id", "Name", }); - } - // @@protoc_insertion_point(outer_class_scope) + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + id_ = 0L; + name_ = ""; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + if (!hasId()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt64(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getNameBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) + return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + @java.lang.Override + protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return PARSER.parseFrom(input); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { + return Builder.create(); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + return newBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return newBuilder(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Foo} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Foo) + org.baeldung.web.dto.FooProtos.FooOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + id_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + } + + public org.baeldung.web.dto.FooProtos.Foo build() { + org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.baeldung.web.dto.FooProtos.Foo buildPartial() { + org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { + if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + return this; + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasName()) { + bitField0_ |= 0x00000002; + name_ = other.name_; + onChanged(); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasId()) { + + return false; + } + if (!hasName()) { + + return false; + } + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private long id_; + + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + /** + * required int64 id = 1; + */ + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + + /** + * required int64 id = 1; + */ + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * required string name = 2; + */ + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + + /** + * required string name = 2; + */ + public Builder setNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Foo) + } + + static { + defaultInstance = new Foo(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:baeldung.Foo) + } + + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor; + private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { + java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + ".dtoB\tFooProtos" }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", }); + } + + // @@protoc_insertion_point(outer_class_scope) } diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java similarity index 100% rename from okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java rename to spring-rest/src/test/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 89% rename from okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 32457fc11b..d1cc67b99a 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -18,12 +18,12 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -public class OkHttpFileUploadingTest { +public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @Test - public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException { + public void whenUploadFile_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -45,7 +45,7 @@ public class OkHttpFileUploadingTest { } @Test - public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException { + public void whenGetUploadFileProgress_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 83% rename from okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index e8edff92df..9a49c8d9a2 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -14,12 +14,12 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpGetTest { +public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; @Test - public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenGetRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -34,7 +34,7 @@ public class OkHttpGetTest { } @Test - public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException { + public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -54,7 +54,7 @@ public class OkHttpGetTest { } @Test - public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() { + public void whenAsynchronousGetRequest_thenCorrect() { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 80% rename from okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 5b2e89eca8..8eddfcb135 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -9,12 +9,12 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpHeaderTest { +public class OkHttpHeaderLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @Test - public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException { + public void whenSetHeader_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -29,7 +29,7 @@ public class OkHttpHeaderTest { } @Test - public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException { + public void whenSetDefaultHeader_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new DefaultContentTypeInterceptor("application/json")) diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java new file mode 100644 index 0000000000..c44500f4be --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -0,0 +1,107 @@ +package org.baeldung.okhttp; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.Cache; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpMiscLiveTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); + + @Test + public void whenSetRequestTimeout_thenFail() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .readTimeout(1, TimeUnit.SECONDS) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenCancelRequest_thenCorrect() throws IOException { + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + final int seconds = 1; + + final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); + + // Schedule a job to cancel the call in 1 second. + executor.schedule(new Runnable() { + public void run() { + + logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); + } + }, seconds, TimeUnit.SECONDS); + + try { + + logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + logger.debug("Call was expected to fail, but completed: " + (System.nanoTime() - startNanos) / 1e9f, response); + + } catch (IOException e) { + + logger.debug("Call failed as expected: " + (System.nanoTime() - startNanos) / 1e9f, e); + } + } + + @Test + public void whenSetResponseCache_thenCorrect() throws IOException { + + int cacheSize = 10 * 1024 * 1024; // 10 MiB + File cacheDirectory = new File("src/test/resources/cache"); + Cache cache = new Cache(cacheDirectory, cacheSize); + + OkHttpClient client = new OkHttpClient.Builder() + .cache(cache) + .build(); + + Request request = new Request.Builder() + .url("http://publicobject.com/helloworld.txt") + .build(); + + Response response1 = client.newCall(request).execute(); + logResponse(response1); + + Response response2 = client.newCall(request).execute(); + logResponse(response2); + } + + private void logResponse(Response response) throws IOException { + + logger.debug("Response response: " + response); + logger.debug("Response cache response: " + response.cacheResponse()); + logger.debug("Response network response: " + response.networkResponse()); + logger.debug("Response responseBody: " + response.body().string()); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 85% rename from okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 1ba2d517c5..18bd4cdcb3 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -18,13 +18,13 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -public class OkHttpPostingTest { +public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; @Test - public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -45,7 +45,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException { + public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { String postBody = "test post"; @@ -64,7 +64,7 @@ public class OkHttpPostingTest { } @Test - public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException { + public void whenPostJson_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); @@ -84,7 +84,7 @@ public class OkHttpPostingTest { } @Test - public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException { + public void whenSendMultipartRequest_thenCorrect() throws IOException { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 80% rename from okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java rename to spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java index 1582a5ff7f..d568a4fdf7 100644 --- a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpRedirectLiveTest.java @@ -12,10 +12,10 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; -public class OkHttpRedirectTest { +public class OkHttpRedirectLiveTest { @Test - public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException { + public void whenSetFollowRedirects_thenNotRedirected() throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(false) diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java similarity index 89% rename from okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java rename to spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java index 6a98f8d20a..255d10b98a 100644 --- a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -1,11 +1,16 @@ package org.baeldung.okhttp; -import okhttp3.MediaType; import okhttp3.RequestBody; -import okio.*; +import okhttp3.MediaType; import java.io.IOException; +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + public class ProgressRequestWrapper extends RequestBody { protected RequestBody delegate; @@ -61,6 +66,7 @@ public class ProgressRequestWrapper extends RequestBody { } public interface ProgressListener { + void onRequestProgress(long bytesWritten, long contentLength); } diff --git a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java index 1344d2d40e..c50e1b4f43 100644 --- a/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/controller/status/ExampleControllerTest.java @@ -32,13 +32,11 @@ public class ExampleControllerTest { @Test public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception { - mockMvc.perform(get("/controller")) - .andExpect(status().isNotAcceptable()); + mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable()); } @Test public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception { - mockMvc.perform(get("/exception")) - .andExpect(status().isForbidden()); + mockMvc.perform(get("/exception")).andExpect(status().isForbidden()); } } diff --git a/spring-rest/src/test/resources/test.txt b/spring-rest/src/test/resources/test.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/spring-rest/src/test/resources/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 5ac974203b..760cf41c63 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -1,2 +1,5 @@ ###The Course The "REST With Spring" Classes: http://github.learnspringsecurity.com + +###Relevant Articles: +- [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) diff --git a/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF b/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-security-custom-permission/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6f460f1751..6098fe5b65 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 com.baeldung @@ -31,7 +32,7 @@ spring-boot-starter-tomcat provided - + org.springframework.boot spring-boot-starter-thymeleaf @@ -41,39 +42,43 @@ org.thymeleaf.extras thymeleaf-extras-springsecurity4 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - + + + + org.springframework.boot + spring-boot-starter-data-jpa + + com.h2database h2 - - - + + + org.springframework.boot + spring-boot-starter-test + test + + junit junit test - + org.hamcrest hamcrest-core test - + org.hamcrest hamcrest-library test - + com.jayway.restassured rest-assured @@ -87,6 +92,48 @@ + + org.springframework + spring-test + test + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + @@ -95,13 +142,107 @@ org.springframework.boot spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + UTF-8 1.8 2.4.0 + 1.6.0 - + diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java index a9d6f3b8b1..b4e8d04b49 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java @@ -2,9 +2,10 @@ package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java new file mode 100644 index 0000000000..1c4cb0124a --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/PersistenceConfig.java @@ -0,0 +1,82 @@ +package org.baeldung.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +public class PersistenceConfig { + + @Autowired + private Environment env; + + public PersistenceConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java index b365744bea..8cc9d45823 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -2,13 +2,17 @@ package org.baeldung.config; import org.baeldung.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @@ -40,4 +44,17 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ; // @formatter:on } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } } \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java index 679dd6c363..f0c3afdf0b 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -2,9 +2,13 @@ package org.baeldung.persistence.dao; import org.baeldung.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.transaction.annotation.Transactional; public interface UserRepository extends JpaRepository { User findByUsername(final String username); + + @Transactional + void removeUserByUsername(String username); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java index 112d502105..67f18c1398 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -12,8 +12,10 @@ import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; +import javax.persistence.Table; @Entity +@Table(name="user_table") public class User { @Id diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties index 0b40f62fa9..9b140b3c69 100644 --- a/spring-security-custom-permission/src/main/resources/application.properties +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -1,6 +1,7 @@ -server.port=8081 +server.port=8082 +server.context-path=/spring-security-custom-permission spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1 +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop diff --git a/spring-security-custom-permission/src/main/resources/persistence-derby.properties b/spring-security-custom-permission/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..fbc0c20144 --- /dev/null +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/CustomUserDetailsServiceTest.java @@ -0,0 +1,72 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; + +import org.baeldung.config.MvcConfig; +import org.baeldung.config.PersistenceConfig; +import org.baeldung.config.SecurityConfig; +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.After; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, SecurityConfig.class, PersistenceConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; + + @Autowired + UserRepository myUserRepository; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Autowired + PasswordEncoder passwordEncoder; + + @Test + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(passwordEncoder.encode(PASSWORD)); + + myUserRepository.save(user); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + } + + @Test(expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + User user = new User(); + user.setUsername(USERNAME); + user.setPassword(passwordEncoder.encode(PASSWORD)); + + myUserRepository.save(user); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + authenticationProvider.authenticate(auth); + } + + @After + public void tearDown() { + myUserRepository.removeUserByUsername(USERNAME); + } + +} diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java index 80b1390083..47626b814a 100644 --- a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -14,24 +14,24 @@ import com.jayway.restassured.specification.RequestSpecification; public class LiveTest { - private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8081/login", "username", "password"); + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8082/spring-security-custom-permission/login", "username", "password"); @Test public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/foos/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { - final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/spring-security-custom-permission/foos"); assertEquals(403, response.getStatusCode()); } @Test public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { - final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/spring-security-custom-permission/foos"); assertEquals(201, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @@ -40,14 +40,14 @@ public class LiveTest { @Test public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/organizations/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/organizations/2"); assertEquals(403, response.getStatusCode()); } @@ -55,7 +55,7 @@ public class LiveTest { @Test public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { - final Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-custom-permission/foos?name=sample"); assertEquals(500, response.getStatusCode()); assertTrue(response.asString().contains("method hasAuthority() not allowed")); } diff --git a/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java index e0f42aa16e..a08079fcff 100644 --- a/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java +++ b/spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java @@ -1,15 +1,13 @@ package org.baeldung.security; +import java.time.LocalDateTime; +import java.util.Collection; + import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - public class MinuteBasedVoter implements AccessDecisionVoter { @Override public boolean supports(ConfigAttribute attribute) { diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index 7cddc42e1d..d1f6b884b1 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -9,7 +9,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Form Login](http://www.baeldung.com/spring-security-login) - [Spring Security Logout](http://www.baeldung.com/spring-security-logout) - [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - +- [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) ### Build the Project ``` diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index c662c32738..e6c77110b3 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -51,9 +51,7 @@ public class MyUserDetailsService implements UserDetailsService { private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = roles.stream() - .map(role -> new SimpleGrantedAuthority(role.toString())) - .collect(Collectors.toList()); + final List authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); return new User(username, password, true, true, true, true, authorities); } diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 854bbb70be..d3f4de9914 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -285,6 +285,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index f369e96ca9..0cec0dc5c3 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -45,7 +45,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java index 817e818b58..2a668f827a 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/ClientLiveTest.java @@ -33,7 +33,7 @@ public class ClientLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); + final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", HttpMethod.GET, null, Foo.class); assertThat(responseEntity.getStatusCode().value(), is(200)); } diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java index 44c5c0cbb1..c27e306c08 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/client/RestClientLiveManualTest.java @@ -30,7 +30,7 @@ import org.springframework.web.client.RestTemplate; * */ public class RestClientLiveManualTest { - final String urlOverHttps = "http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"; + final String urlOverHttps = "http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"; // tests diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 67d9abbae5..616c2a7684 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -37,5 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:on } - } diff --git a/spring-security-rest-digest-auth/pom.xml b/spring-security-rest-digest-auth/pom.xml index bfb4a7223a..1880e12a74 100644 --- a/spring-security-rest-digest-auth/pom.xml +++ b/spring-security-rest-digest-auth/pom.xml @@ -278,6 +278,61 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + 4.2.5.RELEASE @@ -296,7 +351,7 @@ 1.1.3 - 2.7.2 + 2.7.8 5.2.2.Final diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java index 245d5d0a41..cbf6a12ff7 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientNoSpringLiveTest.java @@ -22,16 +22,16 @@ public class ClientNoSpringLiveTest { @Test public final void givenUsingCustomHttpRequestFactory_whenSecuredRestApiIsConsumed_then200OK() { - final HttpHost host = new HttpHost("localhost", 8080, "http"); + final HttpHost host = new HttpHost("localhost", 8082, "http"); final CredentialsProvider credentialsProvider = provider(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).useSystemProperties().build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryDigestAuth(host, client); final RestTemplate restTemplate = new RestTemplate(requestFactory); - // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); + // credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); @@ -46,7 +46,7 @@ public class ClientNoSpringLiveTest { // credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java index b40f9ef472..d673b2633b 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/ClientWithSpringLiveTest.java @@ -23,7 +23,7 @@ public class ClientWithSpringLiveTest { @Test public final void whenSecuredRestApiIsConsumed_then200OK() { - final String uri = "http://localhost:8080/spring-security-rest-digest-auth/api/foos/1"; + final String uri = "http://localhost:8082/spring-security-rest-digest-auth/api/foos/1"; final ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Foo.class); System.out.println(responseEntity.getStatusCode()); diff --git a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java index 93c3af3876..83e888e793 100644 --- a/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java +++ b/spring-security-rest-digest-auth/src/test/java/org/baeldung/client/RawClientLiveTest.java @@ -29,7 +29,7 @@ public class RawClientLiveTest { final int timeout = 20; // seconds final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout).setSocketTimeout(timeout).build(); - final HttpGet getMethod = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/bars/1"); + final HttpGet getMethod = new HttpGet("http://localhost:8082/spring-security-rest-basic-auth/api/bars/1"); getMethod.setConfig(requestConfig); final int hardTimeout = 5; // seconds diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 1cbe1191a8..faeeac1ec2 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -25,6 +25,10 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [REST Query Language with RSQL](http://www.baeldung.com/rest-api-search-language-rsql-fiql) - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [A Guide to CSRF Protection in Spring Security](http://www.baeldung.com/spring-security-csrf) +- [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) +- [Changing Spring Model Parameters with Handler Interceptor](http://www.baeldung.com/spring-model-parameters-with-handler-interceptor) +- [Introduction to Spring MVC HandlerInterceptor](http://www.baeldung.com/spring-mvc-handlerinterceptor) +- [Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions](http://www.baeldung.com/spring-mvc-custom-handler-interceptor) ### Build the Project ``` diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 77b11f1cb1..5cd0ed51f3 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -173,6 +173,11 @@ runtime + + com.h2database + h2 + + @@ -334,7 +339,7 @@ - 8080 + 8082 @@ -381,10 +386,45 @@ - none + **/*LiveTest.java **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + live + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + **/*LiveTest.java @@ -439,7 +479,7 @@ 3.6.2 - 2.7.2 + 2.7.8 1.4.01 diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java index c44e37fee8..f8bc6c0160 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/Application.java @@ -10,7 +10,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter /** * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8080) + * class to run up a Jetty Server (on http://localhost:8082/spring-security-rest-full) * */ @EnableScheduling diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java index 80af01aeeb..3d727fc19f 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/ListenerConfig.java @@ -8,9 +8,9 @@ import org.springframework.web.context.request.RequestContextListener; public class ListenerConfig implements WebApplicationInitializer { - @Override - public void onStartup(ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new RequestContextListener()); - } + @Override + public void onStartup(ServletContext sc) throws ServletException { + // Manages the lifecycle of the root application context + sc.addListener(new RequestContextListener()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java index dad4808a56..f3a87b189e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java @@ -23,7 +23,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:mysql}.properties" }) +@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "org.baeldung.persistence" }) // @ImportResource("classpath*:springDataPersistenceConfig.xml") @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") diff --git a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java index 57e9b32a62..efdb2bc8d4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("org.baeldung.web") @EnableWebMvc -public class WebConfig extends WebMvcConfigurerAdapter{ +public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { super(); @@ -39,11 +39,11 @@ public class WebConfig extends WebMvcConfigurerAdapter{ registry.addViewController("/homepage.html"); } - @Override - public void addInterceptors(final InterceptorRegistry registry) { - registry.addInterceptor(new LoggerInterceptor()); - registry.addInterceptor(new UserInterceptor()); - registry.addInterceptor(new SessionTimerInterceptor()); - } + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(new LoggerInterceptor()); + registry.addInterceptor(new UserInterceptor()); + registry.addInterceptor(new SessionTimerInterceptor()); + } } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java b/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java index 312ead0ab0..603c91007d 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/hateoas/listener/PaginatedResultsRetrievedDiscoverabilityListener.java @@ -77,7 +77,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis } final boolean hasNextPage(final int page, final int totalPages) { - return page < totalPages - 1; + return page < (totalPages - 1); } final boolean hasPreviousPage(final int page) { @@ -89,7 +89,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis } final boolean hasLastPage(final int page, final int totalPages) { - return totalPages > 1 && hasNextPage(page, totalPages); + return (totalPages > 1) && hasNextPage(page, totalPages); } final void appendCommaIfNecessary(final StringBuilder linkHeader) { @@ -102,7 +102,7 @@ class PaginatedResultsRetrievedDiscoverabilityListener implements ApplicationLis protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) { final String resourceName = clazz.getSimpleName().toLowerCase() + "s"; - uriBuilder.path("/" + resourceName); + uriBuilder.path("/auth/" + resourceName); } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java index f5c1626989..90199347b4 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -13,44 +13,41 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SessionTimerInterceptor extends HandlerInterceptorAdapter { - private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); - private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; - @Autowired - private HttpSession session; + @Autowired + private HttpSession session; - /** - * Executed before actual handler is executed - **/ - @Override - public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) - throws Exception { - log.info("Pre handle method - check handling start time"); - long startTime = System.currentTimeMillis(); - request.setAttribute("executionTime", startTime); - if (UserInterceptor.isUserLogged()) { - session = request.getSession(); - log.info("Time since last request in this session: {} ms", - System.currentTimeMillis() - request.getSession().getLastAccessedTime()); - if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { - log.warn("Logging out, due to inactive session"); - SecurityContextHolder.clearContext(); - request.logout(); - response.sendRedirect("/spring-security-rest-full/logout"); - } - } - return true; - } + /** + * Executed before actual handler is executed + **/ + @Override + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { + log.info("Pre handle method - check handling start time"); + long startTime = System.currentTimeMillis(); + request.setAttribute("executionTime", startTime); + if (UserInterceptor.isUserLogged()) { + session = request.getSession(); + log.info("Time since last request in this session: {} ms", System.currentTimeMillis() - request.getSession().getLastAccessedTime()); + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { + log.warn("Logging out, due to inactive session"); + SecurityContextHolder.clearContext(); + request.logout(); + response.sendRedirect("/spring-security-rest-full/logout"); + } + } + return true; + } - /** - * Executed before after handler is executed - **/ - @Override - public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, - final ModelAndView model) throws Exception { - log.info("Post handle method - check execution time of handling"); - long startTime = (Long) request.getAttribute("executionTime"); - log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); - } + /** + * Executed before after handler is executed + **/ + @Override + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView model) throws Exception { + log.info("Post handle method - check execution time of handling"); + long startTime = (Long) request.getAttribute("executionTime"); + log.info("Execution time for handling the request was: {} ms", System.currentTimeMillis() - startTime); + } } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java index 4ba12d0138..6b808d885e 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/interceptor/UserInterceptor.java @@ -31,8 +31,7 @@ public class UserInterceptor extends HandlerInterceptorAdapter { * Executed before after handler is executed. If view is a redirect view, we don't need to execute postHandle **/ @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) - throws Exception { + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception { if (model != null && !isRedirectView(model)) { if (isUserLogged()) { addToModelUserDetails(model); diff --git a/spring-security-rest-full/src/main/resources/application.properties b/spring-security-rest-full/src/main/resources/application.properties new file mode 100644 index 0000000000..58c6f8eec7 --- /dev/null +++ b/spring-security-rest-full/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8082 +server.context-path=/spring-security-rest-full \ No newline at end of file diff --git a/spring-security-rest-full/src/main/resources/data.sql b/spring-security-rest-full/src/main/resources/data.sql new file mode 100644 index 0000000000..5fba12dd85 --- /dev/null +++ b/spring-security-rest-full/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into User (id, firstName, lastName, email, age) values (1, 'john', 'doe', 'john@doe.com', 22); +insert into User (id, firstName, lastName, email, age) values (2, 'tom', 'doe', 'tom@doe.com', 26); + +insert into MyUser (id, firstName, lastName, email, age) values (1, 'john', 'doe', 'john@doe.com', 22); +insert into MyUser (id, firstName, lastName, email, age) values (2, 'tom', 'doe', 'tom@doe.com', 26); diff --git a/spring-security-rest-full/src/main/resources/persistence-h2.properties b/spring-security-rest-full/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..839a466533 --- /dev/null +++ b/spring-security-rest-full/src/main/resources/persistence-h2.properties @@ -0,0 +1,22 @@ +## jdbc.X +#jdbc.driverClassName=com.mysql.jdbc.Driver +#jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true +#jdbc.user=tutorialuser +#jdbc.pass=tutorialmy5ql +# +## hibernate.X +#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +#hibernate.show_sql=false +#hibernate.hbm2ddl.auto=create-drop + + +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java index 9c44d63c4d..e5f0be160f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/Consts.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/Consts.java @@ -1,5 +1,5 @@ package org.baeldung; public interface Consts { - int APPLICATION_PORT = 8080; + int APPLICATION_PORT = 8082; } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java index fb40bd9d62..a1cd9fcfe1 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -51,7 +51,7 @@ import com.google.common.base.Charsets; public class RestTemplateLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; @Before public void beforeTest() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java index 95fce10e45..a2890d8643 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractLiveTest.java @@ -57,7 +57,7 @@ public abstract class AbstractLiveTest { // protected String getURL() { - return "http://localhost:" + APPLICATION_PORT + "/foos"; + return "http://localhost:" + APPLICATION_PORT + "/spring-security-rest-full/auth/foos"; } protected final RequestSpecification givenAuth() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java index f9f9435d75..1d0826e6ba 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java @@ -36,15 +36,15 @@ public class JPACriteriaQueryTest { @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); userApi.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); userApi.save(userTom); @@ -53,8 +53,8 @@ public class JPACriteriaQueryTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "John")); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("firstName", ":", "john")); + params.add(new SearchCriteria("lastName", ":", "doe")); final List results = userApi.searchUser(params); @@ -65,7 +65,7 @@ public class JPACriteriaQueryTest { @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("lastName", ":", "doe")); final List results = userApi.searchUser(params); assertThat(userJohn, isIn(results)); @@ -75,7 +75,7 @@ public class JPACriteriaQueryTest { @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("lastName", ":", "Doe")); + params.add(new SearchCriteria("lastName", ":", "doe")); params.add(new SearchCriteria("age", ">", "25")); final List results = userApi.searchUser(params); @@ -87,8 +87,8 @@ public class JPACriteriaQueryTest { @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { final List params = new ArrayList(); - params.add(new SearchCriteria("firstName", ":", "Adam")); - params.add(new SearchCriteria("lastName", ":", "Fox")); + params.add(new SearchCriteria("firstName", ":", "adam")); + params.add(new SearchCriteria("lastName", ":", "fox")); final List results = userApi.searchUser(params); assertThat(userJohn, not(isIn(results))); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java index b7b38a4fcb..d5fbc819fd 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java @@ -35,15 +35,15 @@ public class JPAQuerydslTest { @Before public void init() { userJohn = new MyUser(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repo.save(userJohn); userTom = new MyUser(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repo.save(userTom); @@ -51,7 +51,7 @@ public class JPAQuerydslTest { @Test public void givenLast_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "Doe"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe"); final Iterable results = repo.findAll(builder.build()); assertThat(results, containsInAnyOrder(userJohn, userTom)); @@ -59,7 +59,7 @@ public class JPAQuerydslTest { @Test public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "John").with("lastName", ":", "Doe"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "john").with("lastName", ":", "doe"); final Iterable results = repo.findAll(builder.build()); @@ -69,7 +69,7 @@ public class JPAQuerydslTest { @Test public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "Doe").with("age", ">", "25"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "doe").with("age", ">", "25"); final Iterable results = repo.findAll(builder.build()); @@ -79,7 +79,7 @@ public class JPAQuerydslTest { @Test public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { - final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "Adam").with("lastName", ":", "Fox"); + final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "adam").with("lastName", ":", "fox"); final Iterable results = repo.findAll(builder.build()); assertThat(results, emptyIterable()); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java index 544161dfd5..3b85cfb487 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationLiveTest.java @@ -3,52 +3,44 @@ package org.baeldung.persistence.query; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; -import org.baeldung.spring.ConfigTest; -import org.baeldung.spring.PersistenceConfig; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class, PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(classes = { ConfigTest.class, PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class JPASpecificationLiveTest { - @Autowired - private UserRepository repository; + // @Autowired + // private UserRepository repository; private User userJohn; private User userTom; - private final String URL_PREFIX = "http://localhost:8080/users/spec?search="; + private final String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/users/spec?search="; @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); - repository.save(userJohn); + // repository.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); - repository.save(userTom); + // repository.save(userTom); } @Test diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java index 97b2274cf9..0d8773dd61 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java @@ -38,15 +38,15 @@ public class JPASpecificationTest { @Before public void init() { userJohn = new User(); - userJohn.setFirstName("John"); - userJohn.setLastName("Doe"); + userJohn.setFirstName("john"); + userJohn.setLastName("doe"); userJohn.setEmail("john@doe.com"); userJohn.setAge(22); repository.save(userJohn); userTom = new User(); - userTom.setFirstName("Tom"); - userTom.setLastName("Doe"); + userTom.setFirstName("tom"); + userTom.setLastName("doe"); userTom.setEmail("tom@doe.com"); userTom.setAge(26); repository.save(userTom); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 13cb92a745..be9b7cf27e 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -public class CsrfAbstractIntegrationTest { +public abstract class CsrfAbstractIntegrationTest { @Autowired private WebApplicationContext context; @@ -41,7 +41,7 @@ public class CsrfAbstractIntegrationTest { } protected RequestPostProcessor testUser() { - return user("user").password("userPass").roles("USER"); + return user("user1").password("user1Pass").roles("USER"); } protected RequestPostProcessor testAdmin() { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index c7caf61525..b04644f847 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -15,12 +15,12 @@ public class CsrfEnabledIntegrationTest extends CsrfAbstractIntegrationTest { @Test public void givenNoCsrf_whenAddFoo_thenForbidden() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden()); + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isForbidden()); } @Test public void givenCsrf_whenAddFoo_thenCreated() throws Exception { - mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated()); + mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser()).with(csrf())).andExpect(status().isCreated()); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java index 99b94cd7b5..ae4a655265 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/SecurityWithCsrfConfig.java @@ -41,7 +41,7 @@ public class SecurityWithCsrfConfig extends WebSecurityConfigurerAdapter { // @formatter:off http .authorizeRequests() - .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") + .antMatchers("/auth/admin/*").hasAnyRole("ROLE_ADMIN") .anyRequest().authenticated() .and() .httpBasic() diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java index 835b32c95c..16ed9db253 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/MyUserLiveTest.java @@ -3,52 +3,28 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import org.baeldung.persistence.model.MyUser; -import org.baeldung.spring.ConfigTest; -import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; import com.jayway.restassured.specification.RequestSpecification; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class MyUserLiveTest { - private ObjectMapper mapper = new ObjectMapper(); - private MyUser userJohn = new MyUser("john", "doe", "john@test.com", 11); - private MyUser userTom = new MyUser("tom", "doe", "tom@test.com", 20); - - private static boolean setupDataCreated = false; - - @Before - public void setupData() throws JsonProcessingException { - if (!setupDataCreated) { - withRequestBody(givenAuth(), userJohn).post("http://localhost:8080/myusers"); - withRequestBody(givenAuth(), userTom).post("http://localhost:8080/myusers"); - setupDataCreated = true; - } - } - + private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11); + private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers"; @Test public void whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers"); + final Response response = givenAuth().get(URL_PREFIX); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenFirstName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?firstName=john"); + final Response response = givenAuth().get(URL_PREFIX + "?firstName=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 1); assertEquals(result[0].getEmail(), userJohn.getEmail()); @@ -56,14 +32,14 @@ public class MyUserLiveTest { @Test public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?lastName=do"); + final Response response = givenAuth().get(URL_PREFIX + "?lastName=do"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @Test public void givenEmail_whenGettingListOfUsers_thenIgnored() { - final Response response = givenAuth().get("http://localhost:8080/api/myusers?email=john"); + final Response response = givenAuth().get(URL_PREFIX + "?email=john"); final MyUser[] result = response.as(MyUser[].class); assertEquals(result.length, 2); } @@ -71,8 +47,4 @@ public class MyUserLiveTest { private RequestSpecification givenAuth() { return RestAssured.given().auth().preemptive().basic("user1", "user1Pass"); } - - private RequestSpecification withRequestBody(final RequestSpecification req, final Object obj) throws JsonProcessingException { - return req.contentType(MediaType.APPLICATION_JSON_VALUE).body(mapper.writeValueAsString(obj)); - } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java index a29de04bb4..916a849c63 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java @@ -30,27 +30,26 @@ import org.springframework.web.context.WebApplicationContext; @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class SessionTimerInterceptorTest { - @Autowired - WebApplicationContext wac; + @Autowired + WebApplicationContext wac; - private MockMvc mockMvc; + private MockMvc mockMvc; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } - /** - * After execution of HTTP GET logs from interceptor will be displayed in - * the console - */ - @Test - public void testInterceptors() throws Exception { - HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn() - .getRequest().getSession(); - Thread.sleep(51000); - mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); - } + /** + * After execution of HTTP GET logs from interceptor will be displayed in + * the console + */ + @Test + public void testInterceptors() throws Exception { + HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn().getRequest().getSession(); + Thread.sleep(51000); + mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful()); + } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java index 0b65311203..ff40c86906 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java @@ -23,8 +23,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional -@ContextConfiguration(classes = {SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class}) -@WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) +@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) +@WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) public class UserInterceptorTest { @Autowired @@ -46,8 +46,7 @@ public class UserInterceptorTest { */ @Test public void testInterceptors() throws Exception { - mockMvc.perform(get("/auth/admin")) - .andExpect(status().is2xxSuccessful()); + mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()); } } diff --git a/spring-security-rest-full/src/test/resources/persistence-mysql.properties b/spring-security-rest-full/src/test/resources/persistence-mysql.properties deleted file mode 100644 index 8263b0d9ac..0000000000 --- a/spring-security-rest-full/src/test/resources/persistence-mysql.properties +++ /dev/null @@ -1,10 +0,0 @@ -# jdbc.X -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 6d492863b4..60f3ed41d1 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -109,7 +109,6 @@ - com.fasterxml.jackson.core jackson-databind @@ -117,7 +116,6 @@ - com.google.guava guava @@ -128,8 +126,8 @@ commons-lang3 ${commons-lang3.version} + - org.slf4j slf4j-api @@ -257,7 +255,7 @@ ${maven-surefire-plugin.version} - + **/*LiveTest.java @@ -289,6 +287,62 @@ + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + 4.2.5.RELEASE @@ -308,7 +362,7 @@ 3.0.1 1.1.0.Final 1.2 - 2.2.2 + 2.7.8 19.0 diff --git a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java index dc3a576b7b..0ef50f745a 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/FooLiveTest.java @@ -17,14 +17,16 @@ import com.jayway.restassured.specification.RequestSpecification; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) public class FooLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest"; // private FormAuthConfig formConfig = new FormAuthConfig(URL_PREFIX + "/login", "temporary", "temporary"); private String cookie; + private RequestSpecification givenAuth() { // return RestAssured.given().auth().form("user", "userPass", formConfig); - if (cookie == null) + if (cookie == null) { cookie = RestAssured.given().contentType("application/x-www-form-urlencoded").formParam("password", "userPass").formParam("username", "user").post(URL_PREFIX + "/login").getCookie("JSESSIONID"); + } return RestAssured.given().cookie("JSESSIONID", cookie); } diff --git a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java index 792b3e28ce..cf1516f8e1 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/SwaggerLiveTest.java @@ -8,7 +8,7 @@ import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Response; public class SwaggerLiveTest { - private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest/api"; + private static final String URL_PREFIX = "http://localhost:8082/spring-security-rest/api"; @Test public void whenVerifySpringFoxIsWorking_thenOK() { diff --git a/spring-security-x509/README.md b/spring-security-x509/README.md new file mode 100644 index 0000000000..2a4b84eae6 --- /dev/null +++ b/spring-security-x509/README.md @@ -0,0 +1,2 @@ +Relevant Articles: +- [X.509 Authentication in Spring Security](http://www.baeldung.com/x-509-authentication-in-spring-security) diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 87fdd64727..8f460c83ec 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -16,12 +16,59 @@ 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java similarity index 85% rename from spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java index 0b9a11552a..5eb1c25ed6 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class X509AuthenticationServerTests { +public class X509AuthenticationServerIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 56cef8ea07..ffddabef40 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -16,12 +16,58 @@ 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java similarity index 85% rename from spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java rename to spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java index 0b9a11552a..5eb1c25ed6 100644 --- a/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerTests.java +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/com/baeldung/spring/security/x509/X509AuthenticationServerIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class X509AuthenticationServerTests { +public class X509AuthenticationServerIntegrationTest { @Test public void contextLoads() { } diff --git a/spring-spel/README.md b/spring-spel/README.md new file mode 100644 index 0000000000..d7e69e114c --- /dev/null +++ b/spring-spel/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Expression Language Guide](http://www.baeldung.com/spring-expression-language) diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 12b7164e27..add5e53348 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -46,7 +46,53 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/spring-spel/src/test/java/com/baeldung/spel/SpelTest.java b/spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java similarity index 99% rename from spring-spel/src/test/java/com/baeldung/spel/SpelTest.java rename to spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java index 5cf18bc1d2..bff42caead 100644 --- a/spring-spel/src/test/java/com/baeldung/spel/SpelTest.java +++ b/spring-spel/src/test/java/com/baeldung/spel/SpelIntegrationTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) -public class SpelTest { +public class SpelIntegrationTest { @Autowired private SpelArithmetic spelArithmetic = new SpelArithmetic(); diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 8cb1c2e982..a8ca755044 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -4,7 +4,8 @@ ### Relevant Articles: - +- [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc) +- [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index a13f1de4c7..e59ce77e57 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,186 +5,247 @@ spring-thymeleaf 0.1-SNAPSHOT war - - 1.8 - - 4.3.3.RELEASE - 3.0.1 - - 1.7.12 - 1.1.3 - - 3.0.1.RELEASE - - 1.1.0.Final - 5.1.2.Final + + 1.8 + + 4.3.3.RELEASE + 3.0.1 + + 1.7.12 + 1.1.3 + + 3.0.1.RELEASE + + 1.1.0.Final + 5.1.2.Final - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 - + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + - - - - org.springframework - spring-context - ${org.springframework-version} - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - ${org.springframework-version} - - - - org.springframework.security - spring-security-web - 4.1.3.RELEASE - - - org.springframework.security - spring-security-config - 4.1.3.RELEASE - - - - org.thymeleaf - thymeleaf - ${org.thymeleaf-version} - - - org.thymeleaf - thymeleaf-spring4 - ${org.thymeleaf-version} - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - javax.servlet - javax.servlet-api - ${javax.servlet-version} - provided - - - - javax.validation - validation-api - ${javax.validation-version} - - - org.hibernate - hibernate-validator - ${org.hibernate-version} - - + + + + org.springframework + spring-context + ${org.springframework-version} + + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + ${org.springframework-version} + + + + org.springframework.security + spring-security-web + 4.1.3.RELEASE + + + org.springframework.security + spring-security-config + 4.1.3.RELEASE + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + 2.0.4 + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-version} + provided + + + + javax.validation + validation-api + ${javax.validation-version} + + + org.hibernate + hibernate-validator + ${org.hibernate-version} + + - - org.springframework - spring-test - 4.1.3.RELEASE - test - + + org.springframework + spring-test + 4.1.3.RELEASE + test + - - - org.springframework.security - spring-security-test - 4.1.3.RELEASE - test - + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + - - - junit - junit - 4.12 - test - + + + junit + junit + 4.12 + test + - + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java-version} - ${java-version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - 8082 - - - - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java-version} + ${java-version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + 8082 + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.0 + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 444b780673..ab048bdd87 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -22,6 +22,9 @@ import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; import com.baeldung.thymeleaf.utils.ArrayUtil; +import nz.net.ultraq.thymeleaf.LayoutDialect; +import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy; + @Configuration @EnableWebMvc @@ -70,6 +73,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application private TemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.setTemplateResolver(templateResolver); return engine; } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java new file mode 100644 index 0000000000..28a38ce30b --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/LayoutDialectController.java @@ -0,0 +1,16 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class LayoutDialectController { + + @RequestMapping(value = "/layout", method = RequestMethod.GET) + public String getNewPage(Model model) { + return "content.html"; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html new file mode 100644 index 0000000000..1184e28e13 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/content.html @@ -0,0 +1,16 @@ + + + +Layout Dialect Example + + +
+

This is a custom content that you can provide

+
+
+

This is some footer content + that you can change

+
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html index a894e41e88..c7d17a4f66 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -6,7 +6,7 @@ - + + +
+

New dialect example

+
+
+

Your page content goes here

+
+
+

My custom footer

+

Your custom footer here

+
+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java similarity index 97% rename from spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index f6a79b7570..0638dbbc11 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) -public class ExpressionUtilityObjectsControllerTest { +public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java new file mode 100644 index 0000000000..23113dc229 --- /dev/null +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -0,0 +1,58 @@ +package com.baeldung.thymeleaf.controller; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class LayoutDialectControllerIntegrationTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void testGetDates() throws Exception{ + mockMvc.perform(get("/layout").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("content.html")); + } + +} diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 93b01ee49c..dc0d4d295c 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -240,39 +240,52 @@ ${maven-surefire-plugin.version} - + **/*IntegrationTest.java - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 4.1.3.RELEASE diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java similarity index 98% rename from spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java rename to spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java index 6e1cd67e06..79d60aa540 100644 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java @@ -25,7 +25,7 @@ import java.util.logging.Logger; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) @WebAppConfiguration -public class CustomUserDetailsServiceTest { +public class CustomUserDetailsServiceIntegrationTest { private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 9eaf4b7c45..99df27f2f9 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -87,5 +87,18 @@ true + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + + + + + + \ No newline at end of file diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.html b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html similarity index 100% rename from wicket/src/main/java/com/baeldung/wicket/examples/Examples.html rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.html diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java similarity index 77% rename from wicket/src/main/java/com/baeldung/wicket/examples/Examples.java rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java index 358e4f7b19..ceb0836467 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/Examples.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorld.java @@ -2,7 +2,7 @@ package com.baeldung.wicket.examples; import org.apache.wicket.markup.html.WebPage; -public class Examples extends WebPage { +public class HelloWorld extends WebPage { private static final long serialVersionUID = 1L; diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java similarity index 80% rename from wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java rename to wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java index 711e8f01fd..079280adce 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/ExamplesApplication.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/HelloWorldApplication.java @@ -4,15 +4,14 @@ import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import com.baeldung.wicket.examples.cafeaddress.CafeAddress; -import com.baeldung.wicket.examples.helloworld.HelloWorld; -public class ExamplesApplication extends WebApplication { +public class HelloWorldApplication extends WebApplication { /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class getHomePage() { - return Examples.class; + return HelloWorld.class; } /** diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java index ce26c5a1ad..86820393c7 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/cafeaddress/CafeAddress.java @@ -1,10 +1,5 @@ package com.baeldung.wicket.examples.cafeaddress; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.WebPage; @@ -13,29 +8,29 @@ import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class CafeAddress extends WebPage { - - private static final long serialVersionUID = 1L; - - String selectedCafe; - Address address; - Map cafeNamesAndAddresses = new HashMap<>(); + private String selectedCafe; + private Address address; + private Map cafeNamesAndAddresses = new HashMap<>(); public CafeAddress(final PageParameters parameters) { super(parameters); initCafes(); - ArrayList cafeNames = new ArrayList<>(this.cafeNamesAndAddresses.keySet()); - this.selectedCafe = cafeNames.get(0); - this.address = new Address(this.cafeNamesAndAddresses.get(this.selectedCafe).getAddress()); + ArrayList cafeNames = new ArrayList<>(cafeNamesAndAddresses.keySet()); + selectedCafe = cafeNames.get(0); + address = new Address(cafeNamesAndAddresses.get(selectedCafe).getAddress()); final Label addressLabel = new Label("address", new PropertyModel(this.address, "address")); addressLabel.setOutputMarkupId(true); - final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel(this, "selectedCafe"), cafeNames); + final DropDownChoice cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<>(this, "selectedCafe"), cafeNames); cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") { - private static final long serialVersionUID = 1L; - @Override protected void onUpdate(AjaxRequestTarget target) { String name = (String) cafeDropdown.getDefaultModel().getObject(); @@ -61,11 +56,11 @@ public class CafeAddress extends WebPage { this.sAddress = address; } - public String getAddress() { + String getAddress() { return this.sAddress; } - public void setAddress(String address) { + void setAddress(String address) { this.sAddress = address; } } diff --git a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java index f819e05be6..6dc7295798 100644 --- a/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java +++ b/wicket/src/main/java/com/baeldung/wicket/examples/helloworld/HelloWorld.java @@ -4,9 +4,6 @@ import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; public class HelloWorld extends WebPage { - - private static final long serialVersionUID = 1L; - public HelloWorld() { add(new Label("hello", "Hello World!")); } diff --git a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java index a393f1d178..7015ffd255 100644 --- a/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java +++ b/wicket/src/main/test/java/com/baeldung/wicket/examples/TestHomePage.java @@ -9,15 +9,15 @@ public class TestHomePage { @Before public void setUp() { - tester = new WicketTester(new ExamplesApplication()); + tester = new WicketTester(new HelloWorldApplication()); } @Test public void whenPageInvoked_thanRenderedOK() { //start and render the test page - tester.startPage(Examples.class); + tester.startPage(HelloWorld.class); //assert rendered page class - tester.assertRenderedPage(Examples.class); + tester.assertRenderedPage(HelloWorld.class); } } diff --git a/wicket/src/main/webapp/WEB-INF/web.xml b/wicket/src/main/webapp/WEB-INF/web.xml index 8a4451c80e..8fc1b1aa95 100644 --- a/wicket/src/main/webapp/WEB-INF/web.xml +++ b/wicket/src/main/webapp/WEB-INF/web.xml @@ -21,7 +21,7 @@ org.apache.wicket.protocol.http.WicketFilter applicationClassName - com.baeldung.wicket.examples.ExamplesApplication + com.baeldung.wicket.examples.HelloWorldApplication diff --git a/xml/README.md b/xml/README.md new file mode 100644 index 0000000000..8531f8b063 --- /dev/null +++ b/xml/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to XPath with Java](http://www.baeldung.com/java-xpath) diff --git a/xmlunit2-tutorial/README.md b/xmlunit2-tutorial/README.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/xmlunit2/README.md b/xmlunit2/README.md new file mode 100644 index 0000000000..72b683796e --- /dev/null +++ b/xmlunit2/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [Introduction To XMLUnit 2.x](http://www.baeldung.com/xmlunit2) diff --git a/xmlunit2-tutorial/pom.xml b/xmlunit2/pom.xml similarity index 96% rename from xmlunit2-tutorial/pom.xml rename to xmlunit2/pom.xml index b4cb684f65..c80e3f37b2 100644 --- a/xmlunit2-tutorial/pom.xml +++ b/xmlunit2/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - xmlunit2-tutorial + xmlunit2 1.0 XMLUnit-2 diff --git a/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 96% rename from xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java index 175250f47b..5af3d48433 100644 --- a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java +++ b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java @@ -1,37 +1,30 @@ package com.baeldung.xmlunit; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; -import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; - -import java.io.File; -import java.util.Iterator; - import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; -import org.xmlunit.diff.ComparisonControllers; -import org.xmlunit.diff.DefaultNodeMatcher; -import org.xmlunit.diff.Diff; -import org.xmlunit.diff.Difference; -import org.xmlunit.diff.ElementSelectors; +import org.xmlunit.diff.*; import org.xmlunit.validation.Languages; import org.xmlunit.validation.ValidationProblem; import org.xmlunit.validation.ValidationResult; import org.xmlunit.validation.Validator; import org.xmlunit.xpath.JAXPXPathEngine; +import java.io.File; +import java.util.Iterator; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.*; +import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; +import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; + public class XMLUnitTest { @Test public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() { diff --git a/xmlunit2-tutorial/src/test/resources/control.xml b/xmlunit2/src/test/resources/control.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/control.xml rename to xmlunit2/src/test/resources/control.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xml b/xmlunit2/src/test/resources/students.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xml rename to xmlunit2/src/test/resources/students.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xsd b/xmlunit2/src/test/resources/students.xsd similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xsd rename to xmlunit2/src/test/resources/students.xsd diff --git a/xmlunit2-tutorial/src/test/resources/students_with_error.xml b/xmlunit2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students_with_error.xml rename to xmlunit2/src/test/resources/students_with_error.xml diff --git a/xmlunit2-tutorial/src/test/resources/teachers.xml b/xmlunit2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/teachers.xml rename to xmlunit2/src/test/resources/teachers.xml diff --git a/xmlunit2-tutorial/src/test/resources/test.xml b/xmlunit2/src/test/resources/test.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/test.xml rename to xmlunit2/src/test/resources/test.xml diff --git a/xstream/README.md b/xstream/README.md new file mode 100644 index 0000000000..e8302c14ef --- /dev/null +++ b/xstream/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +- [XStream User Guide: JSON](http://www.baeldung.com/xstream-json-processing) +- [XStream User Guide: Converting XML to Objects](http://www.baeldung.com/xstream-deserialize-xml-to-object) +- [XStream User Guide: Converting Objects to XML](http://www.baeldung.com/xstream-serialize-object-to-xml)