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 index 1f83ecf934..b3a81aef82 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -13,6 +13,7 @@ UTF-8 3.1.7 4.5.2 + 2.19.1 @@ -28,7 +29,7 @@ 2.19.1 - **/ServiceTest + **/*LiveTest.java 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 index 32689a332f..dba9b9c661 100644 --- 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 @@ -3,6 +3,7 @@ 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; @@ -10,7 +11,7 @@ import java.util.List; public class Course { private int id; private String name; - private List students; + private List students = new ArrayList<>(); public int getId() { return id; @@ -35,31 +36,51 @@ public class Course { public void setStudents(List students) { this.students = students; } - + @GET - @Path("{studentOrder}") - public Student getStudent(@PathParam("studentOrder")int studentOrder) { - return students.get(studentOrder); + @Path("{studentId}") + public Student getStudent(@PathParam("studentId") int studentId) { + return findById(studentId); } - + @POST - public Response postStudent(Student student) { - if (students == null) { - students = new ArrayList<>(); + 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("{studentOrder}") - public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { - Student student = students.get(studentOrder); - if (student != null) { - students.remove(studentOrder); - return Response.ok().build(); - } else { - return Response.notModified().build(); + @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/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java similarity index 50% rename from apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java index 592df4b7c3..a2fd6be435 100644 --- 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/CourseRepository.java @@ -9,7 +9,7 @@ import java.util.Map; @Path("baeldung") @Produces("text/xml") -public class Baeldung { +public class CourseRepository { private Map courses = new HashMap<>(); { @@ -37,26 +37,36 @@ public class Baeldung { } @GET - @Path("courses/{courseOrder}") - public Course getCourse(@PathParam("courseOrder") int courseOrder) { - return courses.get(courseOrder); + @Path("courses/{courseId}") + public Course getCourse(@PathParam("courseId") int courseId) { + return findById(courseId); } @PUT - @Path("courses/{courseOrder}") - public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { - Course existingCourse = courses.get(courseOrder); - - if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { - courses.put(courseOrder, course); - return Response.ok().build(); + @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(); } - - return Response.notModified().build(); + if (existingCourse.equals(course)) { + return Response.notModified().build(); + } + courses.put(courseId, course); + return Response.ok().build(); } - @Path("courses/{courseOrder}/students") - public Course pathToStudent(@PathParam("courseOrder") int courseOrder) { - return courses.get(courseOrder); + @Path("courses/{courseId}/students") + public Course pathToStudent(@PathParam("courseId") int courseId) { + return findById(courseId); } -} \ No newline at end of file + + private Course findById(int id) { + for (Map.Entry course : courses.entrySet()) { + if (course.getKey() == id) { + return course.getValue(); + } + } + return null; + } +} 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 index bb35bab3f8..d3ed2eb70e 100644 --- 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 @@ -7,8 +7,8 @@ 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.setResourceClasses(CourseRepository.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository())); factoryBean.setAddress("http://localhost:8080/"); Server server = factoryBean.create(); @@ -18,4 +18,4 @@ public class RestfulServer { 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 index de782e4edb..bd3dad0f5e 100644 --- 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 @@ -22,4 +22,14 @@ public class Student { 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/student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml similarity index 98% rename from apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml index 7fb6189815..068c9dae4b 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/student.xml +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml @@ -1,4 +1,3 @@ - 3 Student C diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml similarity index 100% rename from apache-cxf/cxf-jaxrs-implementation/src/main/resources/course.xml rename to apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml 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-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java deleted file mode 100644 index 8c606436c8..0000000000 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.baeldung.cxf.jaxrs.implementation; - -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; - -import javax.xml.bind.JAXB; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - -public class ServiceTest { - 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 whenPutCourse_thenCorrect() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "3"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml"); - httpPut.setEntity(new InputStreamEntity(resourceStream)); - httpPut.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPut); - assertEquals(200, response.getStatusLine().getStatusCode()); - - Course course = getCourse(3); - assertEquals(3, course.getId()); - assertEquals("Apache CXF Support for RESTful", course.getName()); - } - - @Test - public void whenPostStudent_thenCorrect() throws IOException { - HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml"); - httpPost.setEntity(new InputStreamEntity(resourceStream)); - httpPost.setHeader("Content-Type", "text/xml"); - - HttpResponse response = client.execute(httpPost); - assertEquals(200, response.getStatusLine().getStatusCode()); - - Student student = getStudent(2, 0); - assertEquals(3, student.getId()); - assertEquals("Student C", student.getName()); - } - - @Test - public void whenDeleteStudent_thenCorrect() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0"); - HttpResponse response = client.execute(httpDelete); - assertEquals(200, response.getStatusLine().getStatusCode()); - - 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 { - URL url = new URL(BASE_URL + courseOrder); - InputStream input = url.openStream(); - return JAXB.unmarshal(new InputStreamReader(input), Course.class); - } - - private Student getStudent(int courseOrder, int studentOrder) throws IOException { - URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); - 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-fop/pom.xml b/apache-fop/pom.xml index 658d567a90..949843a47e 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -97,6 +97,14 @@ 8.0.2 + + org.dbdoclet + herold + 6.1.0 + system + ${basedir}/src/test/resources/jars/herold.jar + + net.sf.jtidy jtidy @@ -132,7 +140,8 @@ ${maven-surefire-plugin.version} - **/*IntegrationTest.java + **/*IntegrationTest.java + **/*LiveTest.java @@ -141,6 +150,42 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + json + + + + + + + + 4.3.11.Final diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java similarity index 98% rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java rename to apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java index bde6868b39..99487c8fdf 100644 --- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java +++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.w3c.dom.Document; import org.w3c.tidy.Tidy; -public class ApacheFOPConvertHTMLTest { +public class ApacheFOPConvertHTMLIntegrationTest { private String inputFile = "src/test/resources/input.html"; private String style = "src/test/resources/xhtml2fo.xsl"; private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl"; diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java similarity index 99% rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java rename to apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java index 5e3c2c472b..9e71cd9c16 100644 --- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java +++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java @@ -30,7 +30,7 @@ import org.dbdoclet.trafo.script.Script; import org.junit.Test; import org.w3c.dom.Document; -public class ApacheFOPHeroldTest { +public class ApacheFOPHeroldLiveTest { private String[] inputUrls = {// @formatter:off "http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/", "http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/", diff --git a/autovalue-tutorial/README.md b/autovalue/README.md similarity index 100% rename from autovalue-tutorial/README.md rename to autovalue/README.md 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/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/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java similarity index 95% rename from cdi/src/test/java/com/baeldung/test/TestInterceptor.java rename to cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java index 3529a796d2..cca8cb7495 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import com.baeldung.interceptor.AuditedInterceptor; import com.baeldung.service.SuperService; -public class TestInterceptor { +public class InterceptorIntegrationTest { Weld weld; WeldContainer container; diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java similarity index 94% rename from cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java rename to cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java index 1f3a8d83e3..f711b0c8ce 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java @@ -16,19 +16,23 @@ import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class TestSpringInterceptor { +public class SpringInterceptorIntegrationTest { @Autowired SpringSuperService springSuperService; @Autowired private List accumulator; + // + @Test public void givenService_whenServiceAndAspectExecuted_thenOk() { String code = "123456"; String result = springSuperService.getInfoFromService(code); + Assert.assertThat(accumulator.size(), is(2)); Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService")); Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService")); } + } diff --git a/core-java-8/README.md b/core-java-8/README.md deleted file mode 100644 index c130e6bd41..0000000000 --- a/core-java-8/README.md +++ /dev/null @@ -1,24 +0,0 @@ -========= - -## Core Java 8 Cookbooks and Examples - -### Relevant Articles: -- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -- [Java – Directory Size](http://www.baeldung.com/java-folder-size) -- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) -- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) -- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) -- [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) -- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) -- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) -- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml deleted file mode 100644 index 22e3bab595..0000000000 --- a/core-java-8/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - 4.0.0 - - com.baeldung - 1.0.0-SNAPSHOT - core-java8 - - core-java8 - - - - - - - commons-io - commons-io - 2.5 - - - - com.google.guava - guava - ${guava.version} - - - - org.apache.commons - commons-collections4 - 4.0 - - - - commons-codec - commons-codec - 1.10 - - - - org.apache.commons - commons-lang3 - 3.3.2 - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - junit - junit - ${junit.version} - test - - - - org.assertj - assertj-core - 3.5.1 - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - core-java-8 - - - 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} - - - - - - - - - UTF-8 - - - 1.7.13 - 1.0.13 - - - 5.1.3.Final - - - 19.0 - 3.4 - - - 1.3 - 4.12 - 1.10.19 - - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - - - - \ No newline at end of file diff --git a/core-java-8/src/main/java/.gitignore b/core-java-8/src/main/java/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-8/src/main/java/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java deleted file mode 100644 index 5bc2d9a9eb..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.enums; - -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.List; -import java.util.stream.Collectors; - -public class Pizza { - - private static EnumSet deliveredPizzaStatuses = - EnumSet.of(PizzaStatusEnum.DELIVERED); - - private PizzaStatusEnum status; - - public enum PizzaStatusEnum { - ORDERED(5) { - @Override - public boolean isOrdered() { - return true; - } - }, - READY(2) { - @Override - public boolean isReady() { - return true; - } - }, - DELIVERED(0) { - @Override - public boolean isDelivered() { - return true; - } - }; - - private int timeToDelivery; - - public boolean isOrdered() { - return false; - } - - public boolean isReady() { - return false; - } - - public boolean isDelivered() { - return false; - } - - public int getTimeToDelivery() { - return timeToDelivery; - } - - PizzaStatusEnum(int timeToDelivery) { - this.timeToDelivery = timeToDelivery; - } - } - - public PizzaStatusEnum getStatus() { - return status; - } - - public void setStatus(PizzaStatusEnum status) { - this.status = status; - } - - public boolean isDeliverable() { - return this.status.isReady(); - } - - public void printTimeToDeliver() { - System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); - } - - public static List getAllUndeliveredPizzas(List input) { - return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); - } - - public static EnumMap> groupPizzaByStatus(List pzList) { - return pzList.stream().collect( - Collectors.groupingBy(Pizza::getStatus, - () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); - } - - public void deliver() { - if (isDeliverable()) { - PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); - this.setStatus(PizzaStatusEnum.DELIVERED); - } - } - -} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java deleted file mode 100644 index ed65919387..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.enums; - -public enum PizzaDeliveryStrategy { - EXPRESS { - @Override - public void deliver(Pizza pz) { - System.out.println("Pizza will be delivered in express mode"); - } - }, - NORMAL { - @Override - public void deliver(Pizza pz) { - System.out.println("Pizza will be delivered in normal mode"); - } - }; - - public abstract void deliver(Pizza pz); -} diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java deleted file mode 100644 index 5ccff5e959..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.enums; - - -public enum PizzaDeliverySystemConfiguration { - INSTANCE; - - PizzaDeliverySystemConfiguration() { - // Do the configuration initialization which - // involves overriding defaults like delivery strategy - } - - private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL; - - public static PizzaDeliverySystemConfiguration getInstance() { - return INSTANCE; - } - - public PizzaDeliveryStrategy getDeliveryStrategy() { - return deliveryStrategy; - } - -} diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip deleted file mode 100644 index 03f840ae2b..0000000000 Binary files a/core-java-8/src/main/resources/compressed.zip and /dev/null differ diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml deleted file mode 100644 index eefdc7a337..0000000000 --- a/core-java-8/src/main/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - \ No newline at end of file diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt deleted file mode 100644 index c57eff55eb..0000000000 --- a/core-java-8/src/main/resources/unzipTest/test1.txt +++ /dev/null @@ -1 +0,0 @@ -Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt deleted file mode 100644 index c57eff55eb..0000000000 --- a/core-java-8/src/main/resources/zipTest/test1.txt +++ /dev/null @@ -1 +0,0 @@ -Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt deleted file mode 100644 index f0fb0f14d1..0000000000 --- a/core-java-8/src/main/resources/zipTest/test2.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is John \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt deleted file mode 100644 index 882edb168e..0000000000 --- a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is Tom \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt deleted file mode 100644 index a78c3fadc8..0000000000 --- a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is Jane \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java deleted file mode 100644 index 8af33393be..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.datetime; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Month; - -import org.junit.Assert; -import org.junit.Test; - -public class UseLocalDateTest { - - UseLocalDate useLocalDate = new UseLocalDate(); - - @Test - public void givenValues_whenUsingFactoryOf_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString()); - } - - @Test - public void givenString_whenUsingParse_thenLocalDate(){ - Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); - } - - @Test - public void whenUsingClock_thenLocalDate(){ - Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock()); - } - - @Test - public void givenDate_whenUsingPlus_thenNextDay(){ - Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now())); - } - - @Test - public void givenDate_whenUsingMinus_thenPreviousDay(){ - Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now())); - } - - @Test - public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){ - Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); - } - - @Test - public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){ - Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth()); - } - - @Test - public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){ - Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); - } - -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java deleted file mode 100644 index 69a289fd02..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.Month; - -import org.junit.Assert; -import org.junit.Test; - -public class UseLocalDateTimeTest { - - UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); - - @Test - public void givenString_whenUsingParse_thenLocalDateTime(){ - Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); - Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java deleted file mode 100644 index 7776fad363..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalTime; - -import org.junit.Assert; -import org.junit.Test; - -public class UseLocalTimeTest { - - UseLocalTime useLocalTime = new UseLocalTime(); - - @Test - public void givenValues_whenUsingFactoryOf_thenLocalTime(){ - Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString()); - } - - @Test - public void givenString_whenUsingParse_thenLocalTime(){ - Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); - } - - @Test - public void givenTime_whenAddHour_thenLocalTime(){ - Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString()); - } - - @Test - public void getHourFromLocalTime(){ - Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1))); - } - - @Test - public void getLocalTimeWithMinuteSetToValue(){ - Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20)); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java deleted file mode 100644 index 5af01ad678..0000000000 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import org.junit.Assert; -import org.junit.Test; - -public class UseZonedDateTimeTest { - - UseZonedDateTime zonedDateTime=new UseZonedDateTime(); - - @Test - public void givenZoneId_thenZonedDateTime(){ - ZoneId zoneId=ZoneId.of("Europe/Paris"); - ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); - Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime)); - } -} 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 deleted file mode 100644 index 62d2663994..0000000000 --- a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.encoderdecoder; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -public class EncoderDecoder { - - @Test - public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { - String plainURL = "http://www.baeldung.com" ; - String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString()); - - Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); - } - - @Test - public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { - String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; - String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString()); - - Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); - } - - @Test - public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { - String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; - - String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); - - Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); - } -} diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt deleted file mode 100644 index 652d70630f..0000000000 --- a/core-java-8/src/test/resources/test.txt +++ /dev/null @@ -1 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index 440af67252..48f0677461 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -18,3 +18,21 @@ - [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) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Random List Element](http://www.baeldung.com/java-random-list-element) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) +- [Java – Directory Size](http://www.baeldung.com/java-folder-size) +- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) +- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) +- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) +- [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) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index 75608b59ba..8b93e238eb 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -162,6 +162,8 @@ **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java @@ -277,6 +279,41 @@ + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/core-java-8/.gitignore b/core-java/src/main/java/com/baeldung/.gitignore similarity index 100% rename from core-java-8/.gitignore rename to core-java/src/main/java/com/baeldung/.gitignore diff --git a/core-java-8/src/main/java/com/baeldung/Adder.java b/core-java/src/main/java/com/baeldung/Adder.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Adder.java rename to core-java/src/main/java/com/baeldung/Adder.java diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java/src/main/java/com/baeldung/AdderImpl.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/AdderImpl.java rename to core-java/src/main/java/com/baeldung/AdderImpl.java diff --git a/core-java-8/src/main/java/com/baeldung/Bar.java b/core-java/src/main/java/com/baeldung/Bar.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Bar.java rename to core-java/src/main/java/com/baeldung/Bar.java diff --git a/core-java-8/src/main/java/com/baeldung/Baz.java b/core-java/src/main/java/com/baeldung/Baz.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Baz.java rename to core-java/src/main/java/com/baeldung/Baz.java diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java/src/main/java/com/baeldung/Foo.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Foo.java rename to core-java/src/main/java/com/baeldung/Foo.java diff --git a/core-java-8/src/main/java/com/baeldung/FooExtended.java b/core-java/src/main/java/com/baeldung/FooExtended.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/FooExtended.java rename to core-java/src/main/java/com/baeldung/FooExtended.java diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java/src/main/java/com/baeldung/UseFoo.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/UseFoo.java rename to core-java/src/main/java/com/baeldung/UseFoo.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/core-java/src/main/java/com/baeldung/datetime/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/README.md rename to core-java/src/main/java/com/baeldung/datetime/README.md diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 74% rename from core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java/src/main/java/com/baeldung/datetime/UseDuration.java index 125b6fbe38..31b45aab84 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java @@ -5,12 +5,12 @@ import java.time.LocalTime; import java.time.Period; public class UseDuration { - - public LocalTime modifyDates(LocalTime localTime,Duration duration){ + + public LocalTime modifyDates(LocalTime localTime, Duration duration) { return localTime.plus(duration); } - - public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){ + + public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) { return Duration.between(localTime1, localTime2); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 67% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java index 47b1b3f67d..82f5745b3c 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; public class UseLocalDate { - - public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){ + + public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { return LocalDate.of(year, month, dayOfMonth); } - - public LocalDate getLocalDateUsingParseMethod(String representation){ + + public LocalDate getLocalDateUsingParseMethod(String representation) { return LocalDate.parse(representation); } - - public LocalDate getLocalDateFromClock(){ + + public LocalDate getLocalDateFromClock() { LocalDate localDate = LocalDate.now(); return localDate; } - - public LocalDate getNextDay(LocalDate localDate){ + + public LocalDate getNextDay(LocalDate localDate) { return localDate.plusDays(1); } - - public LocalDate getPreviousDay(LocalDate localDate){ + + public LocalDate getPreviousDay(LocalDate localDate) { return localDate.minus(1, ChronoUnit.DAYS); } - - public DayOfWeek getDayOfWeek(LocalDate localDate){ + + public DayOfWeek getDayOfWeek(LocalDate localDate) { DayOfWeek day = localDate.getDayOfWeek(); return day; } - - public LocalDate getFirstDayOfMonth(){ + + public LocalDate getFirstDayOfMonth() { LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } - - public LocalDateTime getStartOfDay(LocalDate localDate){ + + public LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 87% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java index 7aa1eaa276..7f39ac2f91 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -3,8 +3,8 @@ package com.baeldung.datetime; import java.time.LocalDateTime; public class UseLocalDateTime { - - public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){ + + public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { return LocalDateTime.parse(representation); } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 67% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java index e13fd10d6f..9bd8f9706c 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java @@ -4,32 +4,32 @@ import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class UseLocalTime { - - public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){ + + public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { LocalTime localTime = LocalTime.of(hour, min, seconds); return localTime; } - - public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){ + + public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { LocalTime localTime = LocalTime.parse(timeRepresentation); return localTime; } - - public LocalTime getLocalTimeFromClock(){ + + public LocalTime getLocalTimeFromClock() { LocalTime localTime = LocalTime.now(); return localTime; } - - public LocalTime addAnHour(LocalTime localTime){ - LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS); + + public LocalTime addAnHour(LocalTime localTime) { + LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS); return newTime; } - - public int getHourFromLocalTime(LocalTime localTime){ + + public int getHourFromLocalTime(LocalTime localTime) { return localTime.getHour(); } - - public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){ + + public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { return localTime.withMinute(minute); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 73% rename from core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java/src/main/java/com/baeldung/datetime/UsePeriod.java index 326cfad650..5a42ef83b4 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java +++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java @@ -4,12 +4,12 @@ import java.time.LocalDate; import java.time.Period; public class UsePeriod { - - public LocalDate modifyDates(LocalDate localDate,Period period){ + + public LocalDate modifyDates(LocalDate localDate, Period period) { return localDate.plus(period); } - - public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){ + + public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { return Period.between(localDate1, localDate2); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 87% rename from core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java/src/main/java/com/baeldung/datetime/UseToInstant.java index 1ddb096cf6..94154ce5c0 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java @@ -6,13 +6,13 @@ import java.util.Calendar; import java.util.Date; public class UseToInstant { - - public LocalDateTime convertDateToLocalDate(Date date){ + + public LocalDateTime convertDateToLocalDate(Date date) { LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return localDateTime; } - - public LocalDateTime convertDateToLocalDate(Calendar calendar){ + + public LocalDateTime convertDateToLocalDate(Calendar calendar) { LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); return localDateTime; } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 90% rename from core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index 0369de9835..2d1b17484b 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -5,8 +5,8 @@ import java.time.ZoneId; import java.time.ZonedDateTime; public class UseZonedDateTime { - - public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){ + + public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); return zonedDateTime; } diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java rename to core-java/src/main/java/com/baeldung/doublecolon/Computer.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java rename to core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java rename to core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java b/core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java rename to core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java b/core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java rename to core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java index 7742781081..bad134bf00 100644 --- a/core-java/src/main/java/com/baeldung/enums/Pizza.java +++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java @@ -1,11 +1,5 @@ package com.baeldung.enums; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.collections15.Predicate; - -import java.io.IOException; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; @@ -13,13 +7,11 @@ import java.util.stream.Collectors; public class Pizza { - private static EnumSet undeliveredPizzaStatuses = - EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY); + private static EnumSet deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED); - private PizzaStatus status; + private PizzaStatusEnum status; - @JsonFormat(shape = JsonFormat.Shape.OBJECT) - public enum PizzaStatus { + public enum PizzaStatusEnum { ORDERED(5) { @Override public boolean isOrdered() { @@ -53,21 +45,20 @@ public class Pizza { return false; } - @JsonProperty("timeToDelivery") public int getTimeToDelivery() { return timeToDelivery; } - PizzaStatus(int timeToDelivery) { + PizzaStatusEnum(int timeToDelivery) { this.timeToDelivery = timeToDelivery; } } - public PizzaStatus getStatus() { + public PizzaStatusEnum getStatus() { return status; } - public void setStatus(PizzaStatus status) { + public void setStatus(PizzaStatusEnum status) { this.status = status; } @@ -80,31 +71,18 @@ public class Pizza { } public static List getAllUndeliveredPizzas(List input) { - return input.stream().filter( - (s) -> undeliveredPizzaStatuses.contains(s.getStatus())) - .collect(Collectors.toList()); + return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); } - public static EnumMap> - groupPizzaByStatus(List pzList) { - return pzList.stream().collect( - Collectors.groupingBy(Pizza::getStatus, - () -> new EnumMap<>(PizzaStatus.class), Collectors.toList())); + public static EnumMap> groupPizzaByStatus(List pzList) { + return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); } public void deliver() { if (isDeliverable()) { PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); - this.setStatus(PizzaStatus.DELIVERED); + this.setStatus(PizzaStatusEnum.DELIVERED); } } - public static String getJsonString(Pizza pz) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz); - } - - private static Predicate thatAreNotDelivered() { - return entry -> undeliveredPizzaStatuses.contains(entry.getStatus()); - } } \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/README.md b/core-java/src/main/java/com/baeldung/enums/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/README.md rename to core-java/src/main/java/com/baeldung/enums/README.md diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java similarity index 89% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java index d4a6a0f42e..5a13f505c2 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java @@ -1,7 +1,5 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; -import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Set; @@ -10,7 +8,7 @@ public class ComplexClass { private List genericList; private Set integerSet; - public ComplexClass(ArrayList genericArrayList, HashSet integerHashSet) { + public ComplexClass(List genericArrayList, Set integerHashSet) { super(); this.genericList = genericArrayList; this.integerSet = integerHashSet; diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java index ebe005688c..29b280865e 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public class PrimitiveClass { diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java index 1e1423f0b3..168e3af0c6 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public class Rectangle extends Shape { private double width; diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java similarity index 70% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java index 3bfc81da8f..628359becf 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; public abstract class Shape { public abstract double area(); diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java similarity index 96% rename from core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java rename to core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java index f11e34f0ba..b9125c3e2f 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java +++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java @@ -1,4 +1,4 @@ -package org.baeldung.equalshashcode.entities; +package com.baeldung.equalshashcode.entities; import java.awt.Color; diff --git a/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java new file mode 100644 index 0000000000..6c79e89717 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java @@ -0,0 +1,11 @@ +package com.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/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java similarity index 94% rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index f1ab2d8d09..ae79787570 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction { private Collection createSubtasks() { - List subtasks = - new ArrayList<>(); + List subtasks = new ArrayList<>(); String partOne = workLoad.substring(0, workLoad.length() / 2); String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length()); diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java similarity index 60% rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java index 5d4d97b805..af9805c33f 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask { if (arr.length > THRESHOLD) { - return ForkJoinTask.invokeAll(createSubtasks()) - .stream() - .mapToInt(ForkJoinTask::join) - .sum(); + return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum(); } else { return processing(arr); @@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask { private Collection createSubtasks() { List dividedTasks = new ArrayList<>(); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, 0, arr.length / 2))); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, arr.length / 2, arr.length))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length))); return dividedTasks; } private Integer processing(int[] arr) { - return Arrays.stream(arr) - .filter(a -> a > 10 && a < 27) - .map(a -> a * 10) - .sum(); + return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum(); } } diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java similarity index 99% rename from core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java rename to core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java index 521616600f..fd24a6fc66 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin.util; - import java.util.concurrent.ForkJoinPool; public class PoolUtil { diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java new file mode 100644 index 0000000000..0d66406ac2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java @@ -0,0 +1,56 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; +import java.util.List; + +public class PersistentCookieStore implements CookieStore, Runnable { + CookieStore store; + + public PersistentCookieStore() { + store = new CookieManager().getCookieStore(); + // deserialize cookies into store + Runtime.getRuntime().addShutdownHook(new Thread(this)); + } + + @Override + public void run() { + // serialize cookies to persistent storage + } + + @Override + public void add(URI uri, HttpCookie cookie) { + store.add(uri, cookie); + + } + + @Override + public List get(URI uri) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getCookies() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getURIs() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean remove(URI uri, HttpCookie cookie) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean removeAll() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java new file mode 100644 index 0000000000..6d6371bfe0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java @@ -0,0 +1,26 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; + +public class ProxyAcceptCookiePolicy implements CookiePolicy { + String acceptedProxy; + + public ProxyAcceptCookiePolicy(String acceptedProxy) { + this.acceptedProxy = acceptedProxy; + } + + public boolean shouldAccept(URI uri, HttpCookie cookie) { + String host; + try { + host = InetAddress.getByName(uri.getHost()).getCanonicalHostName(); + } catch (UnknownHostException e) { + host = uri.getHost(); + } + + if (!HttpCookie.domainMatches(acceptedProxy, host)) { + return false; + } + + return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java new file mode 100644 index 0000000000..916442533b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoClient { + private DatagramSocket socket; + private InetAddress address; + + private byte[] buf; + + public EchoClient() { + try { + socket = new DatagramSocket(); + address = InetAddress.getByName("localhost"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public String sendEcho(String msg) { + DatagramPacket packet = null; + try { + buf = msg.getBytes(); + packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } catch (IOException e) { + e.printStackTrace(); + } + String received = new String(packet.getData(), 0, packet.getLength()); + return received; + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java new file mode 100644 index 0000000000..900d330786 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public EchoServer() throws IOException { + socket = new DatagramSocket(4445); + } + + public void run() { + running = true; + + while (running) { + try { + + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} 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 index 1c034051aa..61f339db58 100644 --- 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 @@ -17,6 +17,11 @@ public class EchoClient { return instance; } + public static void stop() throws IOException { + client.close(); + buffer = null; + } + private EchoClient() { try { client = SocketChannel.open(new InetSocketAddress("localhost", 5454)); @@ -42,5 +47,4 @@ public class EchoClient { 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 index aedcbb319b..2ed9a27c4c 100644 --- 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 @@ -1,20 +1,19 @@ 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.nio.channels.Selector; -import java.nio.channels.SelectionKey; -import java.nio.ByteBuffer; -import java.io.IOException; -import java.util.Set; import java.util.Iterator; -import java.net.InetSocketAddress; +import java.util.Set; public class EchoServer { - public static void main(String[] args) - - throws IOException { + public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); @@ -47,4 +46,15 @@ public class EchoServer { } } } + + 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(); + } } diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java/src/main/java/com/baeldung/java_8_features/Address.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Address.java rename to core-java/src/main/java/com/baeldung/java_8_features/Address.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java/src/main/java/com/baeldung/java_8_features/CustomException.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java rename to core-java/src/main/java/com/baeldung/java_8_features/CustomException.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java/src/main/java/com/baeldung/java_8_features/Detail.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java rename to core-java/src/main/java/com/baeldung/java_8_features/Detail.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java/src/main/java/com/baeldung/java_8_features/User.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/User.java rename to core-java/src/main/java/com/baeldung/java_8_features/User.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java similarity index 89% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java rename to core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java index 011173bcaf..045fc90590 100644 --- a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java @@ -9,7 +9,7 @@ public interface Vehicle { } default long[] startPosition() { - return new long[]{23, 15}; + return new long[] { 23, 15 }; } default String getOverview() { diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java similarity index 63% rename from core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java rename to core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java index 83e55f5f4d..64bec0246d 100644 --- a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java @@ -1,9 +1,9 @@ package com.baeldung.java_8_features; -public class VehicleImpl implements Vehicle { +public class VehicleImpl implements Vehicle { @Override public void moveTo(long altitude, long longitude) { - //do nothing + // do nothing } } 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..7f87b47476 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -0,0 +1,22 @@ +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 { + 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/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java new file mode 100644 index 0000000000..570bd60b2d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -0,0 +1,41 @@ +package com.baeldung.socket; + +import java.io.*; +import java.net.*; + +public class EchoClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { + System.out.print(e); + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java new file mode 100644 index 0000000000..b920967545 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -0,0 +1,70 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoMultiServer { + private ServerSocket serverSocket; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + while (true) + new EchoClientHandler(serverSocket.accept()).run(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + stop(); + } + + } + + public void stop() { + try { + + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private static class EchoClientHandler extends Thread { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public EchoClientHandler(Socket socket) { + this.clientSocket = socket; + } + + public void run() { + try { + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("bye"); + break; + } + out.println(inputLine); + } + + in.close(); + out.close(); + clientSocket.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] args) { + EchoMultiServer server = new EchoMultiServer(); + server.start(5555); + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java new file mode 100644 index 0000000000..dfd281d51c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -0,0 +1,49 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("good bye"); + break; + } + out.println(inputLine); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + EchoServer server = new EchoServer(); + server.start(4444); + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java new file mode 100644 index 0000000000..e6f14bb2b6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -0,0 +1,44 @@ +package com.baeldung.socket; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +public class GreetClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { + + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java new file mode 100644 index 0000000000..05bc65a65e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/GreetServer.java @@ -0,0 +1,46 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class GreetServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String greeting = in.readLine(); + if ("hello server".equals(greeting)) + out.println("hello client"); + else + out.println("unrecognised greeting"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + GreetServer server = new GreetServer(); + server.start(6666); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java/src/main/java/com/baeldung/streamApi/Product.java similarity index 99% rename from core-java-8/src/main/java/com/baeldung/streamApi/Product.java rename to core-java/src/main/java/com/baeldung/streamApi/Product.java index 18f3a61904..26b8bd6fed 100644 --- a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java +++ b/core-java/src/main/java/com/baeldung/streamApi/Product.java @@ -44,7 +44,6 @@ public class Product { this.name = name; } - public static Stream streamOf(List list) { return (list == null || list.isEmpty()) ? Stream.empty() : list.stream(); } diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java similarity index 66% rename from core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java rename to core-java/src/main/java/com/baeldung/threadpool/CountingTask.java index 05aa14c5ae..effdf54916 100644 --- a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java +++ b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask { @Override protected Integer compute() { - return node.value + node.children.stream() - .map(childNode -> new CountingTask(childNode).fork()) - .collect(Collectors.summingInt(ForkJoinTask::join)); + return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join)); } } diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java rename to core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java rename to core-java/src/main/java/com/baeldung/threadpool/TreeNode.java diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java/src/main/java/com/baeldung/unzip/UnzipFile.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java rename to core-java/src/main/java/com/baeldung/unzip/UnzipFile.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java/src/main/java/com/baeldung/zip/ZipDirectory.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java rename to core-java/src/main/java/com/baeldung/zip/ZipDirectory.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java/src/main/java/com/baeldung/zip/ZipFile.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipFile.java rename to core-java/src/main/java/com/baeldung/zip/ZipFile.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java rename to core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.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 deleted file mode 100644 index 2c52a17904..0000000000 --- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ /dev/null @@ -1,11 +0,0 @@ -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/main/resources/dirCompressed.zip b/core-java/src/main/resources/dirCompressed.zip similarity index 100% rename from core-java-8/src/main/resources/dirCompressed.zip rename to core-java/src/main/resources/dirCompressed.zip diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java/src/main/resources/fileTest.txt similarity index 100% rename from core-java-8/src/main/resources/fileTest.txt rename to core-java/src/main/resources/fileTest.txt diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java/src/main/resources/multiCompressed.zip similarity index 100% rename from core-java-8/src/main/resources/multiCompressed.zip rename to core-java/src/main/resources/multiCompressed.zip diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp new file mode 100644 index 0000000000..20f137b416 --- /dev/null +++ b/core-java/src/main/resources/targetFile.tmp @@ -0,0 +1,2 @@ +line 1 +a second line \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 87% rename from core-java-8/src/test/java/com/baeldung/CharToStringTest.java rename to core-java/src/test/java/com/baeldung/CharToStringUnitTest.java index d91016d104..78742e356d 100644 --- a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java +++ b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java @@ -4,10 +4,10 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -public class CharToStringTest { +public class CharToStringUnitTest { @Test - public void givenChar_whenCallingStringValueOf_shouldConvertToString(){ + public void givenChar_whenCallingStringValueOf_shouldConvertToString() { final char givenChar = 'x'; final String result = String.valueOf(givenChar); @@ -16,7 +16,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){ + public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() { final char givenChar = 'x'; final String result = Character.toString(givenChar); @@ -25,7 +25,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){ + public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() { final char givenChar = 'x'; final String result = new Character(givenChar).toString(); @@ -34,7 +34,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenConcatenated_shouldConvertToString4(){ + public void givenChar_whenConcatenated_shouldConvertToString4() { final char givenChar = 'x'; final String result = givenChar + ""; @@ -43,7 +43,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenFormated_shouldConvertToString5(){ + public void givenChar_whenFormated_shouldConvertToString5() { final char givenChar = 'x'; final String result = String.format("%c", givenChar); diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/RandomListElementTest.java rename to core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java index 1918c801dc..6ae7c40f4d 100644 --- a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java +++ b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.util.*; import java.util.concurrent.ThreadLocalRandom; -public class RandomListElementTest { +public class RandomListElementUnitTest { @Test public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { @@ -20,7 +20,7 @@ public class RandomListElementTest { public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { List givenList = Lists.newArrayList(1, 2, 3); - givenList.get((int)(Math.random() * givenList.size())); + givenList.get((int) (Math.random() * givenList.size())); } @Test diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java rename to core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java index 6c1493d89b..a7ad0bf114 100644 --- a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java +++ b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung; -import com.google.common.primitives.Ints; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; -public class StringToIntOrIntegerTest { +import org.junit.Test; + +import com.google.common.primitives.Ints; + +public class StringToIntOrIntegerUnitTest { @Test public void givenString_whenParsingInt_shouldConvertToInt() { @@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest { assertThat(result).isEqualTo(42); } - @Test public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { String givenString = "42"; diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java similarity index 54% rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java rename to core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java index d94f72b685..dbddbe6c54 100644 --- a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java +++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java @@ -36,198 +36,143 @@ import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class Java8CollectorsTest { +public class Java8CollectorsUnitTest { private final List givenList = Arrays.asList("a", "bb", "ccc", "dd"); @Test public void whenCollectingToList_shouldCollectToList() throws Exception { - final List result = givenList.stream() - .collect(toList()); + final List result = givenList.stream().collect(toList()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToList_shouldCollectToSet() throws Exception { - final Set result = givenList.stream() - .collect(toSet()); + final Set result = givenList.stream().collect(toSet()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { - final List result = givenList.stream() - .collect(toCollection(LinkedList::new)); + final List result = givenList.stream().collect(toCollection(LinkedList::new)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(LinkedList.class); + assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class); } @Test public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { assertThatThrownBy(() -> { - givenList.stream() - .collect(toCollection(ImmutableList::of)); + givenList.stream().collect(toCollection(ImmutableList::of)); }).isInstanceOf(UnsupportedOperationException.class); } @Test public void whenCollectingToMap_shouldCollectToMap() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingAndThen_shouldCollect() throws Exception { - final List result = givenList.stream() - .collect(collectingAndThen(toList(), ImmutableList::copyOf)); + final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(ImmutableList.class); + assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class); } @Test public void whenJoining_shouldJoin() throws Exception { - final String result = givenList.stream() - .collect(joining()); + final String result = givenList.stream().collect(joining()); - assertThat(result) - .isEqualTo("abbcccdd"); + assertThat(result).isEqualTo("abbcccdd"); } @Test public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { - final String result = givenList.stream() - .collect(joining(" ")); + final String result = givenList.stream().collect(joining(" ")); - assertThat(result) - .isEqualTo("a bb ccc dd"); + assertThat(result).isEqualTo("a bb ccc dd"); } @Test public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { - final String result = givenList.stream() - .collect(joining(" ", "PRE-", "-POST")); + final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST")); - assertThat(result) - .isEqualTo("PRE-a bb ccc dd-POST"); + assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); } @Test public void whenPartitioningBy_shouldPartition() throws Exception { - final Map> result = givenList.stream() - .collect(partitioningBy(s -> s.length() > 2)); + final Map> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2)); - assertThat(result) - .containsKeys(true, false) - .satisfies(booleanListMap -> { - assertThat(booleanListMap.get(true)) - .contains("ccc"); + assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> { + assertThat(booleanListMap.get(true)).contains("ccc"); - assertThat(booleanListMap.get(false)) - .contains("a", "bb", "dd"); - }); + assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); + }); } @Test public void whenCounting_shouldCount() throws Exception { - final Long result = givenList.stream() - .collect(counting()); + final Long result = givenList.stream().collect(counting()); - assertThat(result) - .isEqualTo(4); + assertThat(result).isEqualTo(4); } @Test public void whenSummarizing_shouldSummarize() throws Exception { - final DoubleSummaryStatistics result = givenList.stream() - .collect(summarizingDouble(String::length)); + final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length)); - assertThat(result.getAverage()) - .isEqualTo(2); - assertThat(result.getCount()) - .isEqualTo(4); - assertThat(result.getMax()) - .isEqualTo(3); - assertThat(result.getMin()) - .isEqualTo(1); - assertThat(result.getSum()) - .isEqualTo(8); + assertThat(result.getAverage()).isEqualTo(2); + assertThat(result.getCount()).isEqualTo(4); + assertThat(result.getMax()).isEqualTo(3); + assertThat(result.getMin()).isEqualTo(1); + assertThat(result.getSum()).isEqualTo(8); } @Test public void whenAveraging_shouldAverage() throws Exception { - final Double result = givenList.stream() - .collect(averagingDouble(String::length)); + final Double result = givenList.stream().collect(averagingDouble(String::length)); - assertThat(result) - .isEqualTo(2); + assertThat(result).isEqualTo(2); } @Test public void whenSumming_shouldSum() throws Exception { - final Double result = givenList.stream() - .collect(summingDouble(String::length)); + final Double result = givenList.stream().collect(summingDouble(String::length)); - assertThat(result) - .isEqualTo(8); + assertThat(result).isEqualTo(8); } @Test public void whenMaxingBy_shouldMaxBy() throws Exception { - final Optional result = givenList.stream() - .collect(maxBy(Comparator.naturalOrder())); + final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder())); - assertThat(result) - .isPresent() - .hasValue("dd"); + assertThat(result).isPresent().hasValue("dd"); } @Test public void whenGroupingBy_shouldGroupBy() throws Exception { - final Map> result = givenList.stream() - .collect(groupingBy(String::length, toSet())); + final Map> result = givenList.stream().collect(groupingBy(String::length, toSet())); - assertThat(result) - .containsEntry(1, newHashSet("a")) - .containsEntry(2, newHashSet("bb", "dd")) - .containsEntry(3, newHashSet("ccc")); + assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc")); } - @Test public void whenCreatingCustomCollector_shouldCollect() throws Exception { - final ImmutableSet result = givenList.stream() - .collect(toImmutableSet()); + final ImmutableSet result = givenList.stream().collect(toImmutableSet()); - assertThat(result) - .isInstanceOf(ImmutableSet.class) - .contains("a", "bb", "ccc", "dd"); + assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd"); } diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java similarity index 88% rename from core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java index 5363a73afa..df12c3d79e 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java @@ -1,24 +1,26 @@ package com.baeldung.completablefuture; -import java.util.concurrent.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CompletableFutureTest { +public class CompletableFutureUnitTest { @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { - Future completableFuture = calculateAsync(); String result = completableFuture.get(); assertEquals("Hello", result); - } public Future calculateAsync() throws InterruptedException { @@ -35,15 +37,12 @@ public class CompletableFutureTest { @Test public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { - Future completableFuture = CompletableFuture.completedFuture("Hello"); String result = completableFuture.get(); assertEquals("Hello", result); - } - public Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); @@ -56,90 +55,67 @@ public class CompletableFutureTest { return completableFuture; } - @Test(expected = CancellationException.class) public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { - Future future = calculateAsyncWithCancellation(); future.get(); - } @Test public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { - CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); assertEquals("Hello", future.get()); - } @Test public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); future.get(); - } @Test public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); future.get(); - } @Test public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApply(s -> s + " World"); assertEquals("Hello World", future.get()); - } @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCombine(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture.supplyAsync(() -> "Hello") - .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> System.out.println(s1 + s2)); - + CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); } @Test public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { - CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); @@ -154,17 +130,13 @@ public class CompletableFutureTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3) - .map(CompletableFuture::join) - .collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); - } @Test public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { - String name = null; // ... @@ -177,12 +149,10 @@ public class CompletableFutureTest { }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); - } @Test(expected = ExecutionException.class) public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = new CompletableFuture<>(); // ... @@ -192,18 +162,15 @@ public class CompletableFutureTest { // ... completableFuture.get(); - } @Test public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); assertEquals("Hello World", future.get()); - } } \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java rename to core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java index 4bce40c2d9..e4753dbd5c 100644 --- a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java +++ b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java @@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit; import static org.assertj.core.api.Assertions.assertThat; -public class JavaUtilTimeTest { +public class JavaUtilTimeUnitTest { @Test public void currentTime() { diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java new file mode 100644 index 0000000000..57e1f33280 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.datetime; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; + +import org.junit.Assert; +import org.junit.Test; + +public class UseLocalDateTimeUnitTest { + + UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); + + @Test + public void givenString_whenUsingParse_thenLocalDateTime() { + Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); + Assert.assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); + } +} diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java new file mode 100644 index 0000000000..8f1997e9e8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.datetime; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; + +import org.junit.Assert; +import org.junit.Test; + +public class UseLocalDateUnitTest { + + UseLocalDate useLocalDate = new UseLocalDate(); + + @Test + public void givenValues_whenUsingFactoryOf_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); + } + + @Test + public void givenString_whenUsingParse_thenLocalDate() { + Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + } + + @Test + public void whenUsingClock_thenLocalDate() { + Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()); + } + + @Test + public void givenDate_whenUsingPlus_thenNextDay() { + Assert.assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); + } + + @Test + public void givenDate_whenUsingMinus_thenPreviousDay() { + Assert.assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); + } + + @Test + public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { + Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))); + } + + @Test + public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { + Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + } + + @Test + public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { + Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); + } + +} diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java new file mode 100644 index 0000000000..996e200ae9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import java.time.LocalTime; + +import org.junit.Assert; +import org.junit.Test; + +public class UseLocalTimeUnitTest { + + UseLocalTime useLocalTime = new UseLocalTime(); + + @Test + public void givenValues_whenUsingFactoryOf_thenLocalTime() { + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()); + } + + @Test + public void givenString_whenUsingParse_thenLocalTime() { + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); + } + + @Test + public void givenTime_whenAddHour_thenLocalTime() { + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()); + } + + @Test + public void getHourFromLocalTime() { + Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1))); + } + + @Test + public void getLocalTimeWithMinuteSetToValue() { + Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20)); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 63% rename from core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java rename to core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java index 8a3228aaa5..7c030c328a 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java @@ -1,29 +1,26 @@ package com.baeldung.datetime; import java.time.LocalDate; -import java.time.LocalDateTime; import java.time.Period; -import java.time.ZoneId; -import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Test; -public class UsePeriodTest { - UsePeriod usingPeriod=new UsePeriod(); - +public class UsePeriodUnitTest { + UsePeriod usingPeriod = new UsePeriod(); + @Test - public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){ + public void givenPeriodAndLocalDate_thenCalculateModifiedDate() { Period period = Period.ofDays(1); LocalDate localDate = LocalDate.parse("2007-05-10"); - Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period)); + Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period)); } - + @Test - public void givenDates_thenGetPeriod(){ + public void givenDates_thenGetPeriod() { LocalDate localDate1 = LocalDate.parse("2007-05-10"); LocalDate localDate2 = LocalDate.parse("2007-05-15"); - + Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2)); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java new file mode 100644 index 0000000000..5fb079b94c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Assert; +import org.junit.Test; + +public class UseZonedDateTimeUnitTest { + + UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + + @Test + public void givenZoneId_thenZonedDateTime() { + ZoneId zoneId = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); + Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java rename to core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java index 85194f5aa6..f69e4b03ee 100644 --- a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java +++ b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java @@ -13,7 +13,7 @@ import java.util.function.BiFunction; import static com.baeldung.doublecolon.ComputerUtils.*; -public class TestComputerUtils { +public class ComputerUtilsUnitTest { @Before public void setup() { diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java new file mode 100644 index 0000000000..c944dfa6fe --- /dev/null +++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java @@ -0,0 +1,77 @@ +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.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 static java.util.stream.Collectors.joining; + +public class EncoderDecoderUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class); + private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; + + 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(testUrl); + + 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 encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", "")); + + Assert.assertThat(testUrl, CoreMatchers.is(encodedURL)); + } + + @Test + public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception { + URL url = new URL(testUrl); + + String query = url.getQuery(); + + String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(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/enums/PizzaTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java rename to core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index deeebaa240..6cf6ad3551 100644 --- a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.enums; - import org.junit.Test; import java.util.ArrayList; @@ -9,7 +8,7 @@ import java.util.List; import static junit.framework.TestCase.assertTrue; -public class PizzaTest { +public class PizzaUnitTest { @Test public void givenPizaOrder_whenReady_thenDeliverable() { diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java rename to core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java index e21af9552a..3319716dc6 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java @@ -1,11 +1,5 @@ package com.baeldung.file; -import org.apache.commons.io.FileUtils; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -20,7 +14,13 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; -public class FileOperationsTest { +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +public class FileOperationsUnitTest { @Test public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { @@ -30,15 +30,15 @@ public class FileOperationsTest { File file = new File(classLoader.getResource("fileTest.txt").getFile()); InputStream inputStream = new FileInputStream(file); String data = readFromInputStream(inputStream); - + Assert.assertEquals(expectedData, data.trim()); } @Test public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - - Class clazz = FileOperationsTest.class; + + Class clazz = FileOperationsUnitTest.class; InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); String data = readFromInputStream(inputStream); @@ -69,44 +69,44 @@ public class FileOperationsTest { Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); } - + @Test public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - + ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); String data = FileUtils.readFileToString(file); - + Assert.assertEquals(expectedData, data.trim()); } - + @Test public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { String expectedData = "Hello World from fileTest.txt!!!"; Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - + byte[] fileBytes = Files.readAllBytes(path); String data = new String(fileBytes); Assert.assertEquals(expectedData, data.trim()); } - + @Test public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { String expectedData = "Hello World from fileTest.txt!!!"; Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - + 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 { StringBuilder resultStringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java similarity index 89% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java rename to core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index ce878026d4..6f3384c8eb 100644 --- a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -1,5 +1,9 @@ package com.baeldung.functionalinterface; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -10,57 +14,43 @@ 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.*; +import com.google.common.util.concurrent.Uninterruptibles; -public class FunctionalInterfaceTest { +public class FunctionalInterfaceUnitTest { @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", s -> s.length()); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - } @Test public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", String::length); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - - } - - public byte[] transformArray(short[] array, ShortToByteFunction function) { - byte[] transformedArray = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - transformedArray[i] = function.applyAsByte(array[i]); - } - return transformedArray; } @Test public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() { - short[] array = {(short) 1, (short) 2, (short) 3}; + short[] array = { (short) 1, (short) 2, (short) 3 }; byte[] transformedArray = transformArray(array, s -> (byte) (s * 2)); - byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6}; + byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 }; assertArrayEquals(expectedArray, transformedArray); } @Test public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() { - Map salaries = new HashMap<>(); salaries.put("John", 40000); salaries.put("Freddy", 30000); @@ -71,22 +61,18 @@ public class FunctionalInterfaceTest { assertEquals(new Integer(50000), salaries.get("John")); assertEquals(new Integer(30000), salaries.get("Freddy")); assertEquals(new Integer(60000), salaries.get("Samuel")); - } - @Test public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { - Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); thread.start(); - } @Test public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() { - int[] fibs = {0, 1}; + int[] fibs = { 0, 1 }; Stream fibonacci = Stream.generate(() -> { int result = fibs[1]; int fib3 = fibs[0] + fibs[1]; @@ -95,55 +81,44 @@ public class FunctionalInterfaceTest { return result; }); - List fibonacci5 = fibonacci.limit(5) - .collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); assertEquals(new Integer(2), fibonacci5.get(2)); assertEquals(new Integer(3), fibonacci5.get(3)); assertEquals(new Integer(5), fibonacci5.get(4)); - } @Test public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { - List names = Arrays.asList("John", "Freddy", "Samuel"); names.forEach(name -> System.out.println("Hello, " + name)); - } @Test public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() { - Map ages = new HashMap<>(); ages.put("John", 25); ages.put("Freddy", 24); ages.put("Samuel", 30); ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); - } @Test public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { - List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream() - .filter(name -> name.startsWith("A")) - .collect(Collectors.toList()); + List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); assertTrue(namesWithA.contains("Aaron")); - } @Test public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() { - List names = Arrays.asList("bob", "josh", "megan"); names.replaceAll(String::toUpperCase); @@ -151,7 +126,6 @@ public class FunctionalInterfaceTest { assertEquals("BOB", names.get(0)); assertEquals("JOSH", names.get(1)); assertEquals("MEGAN", names.get(2)); - } @Test @@ -159,8 +133,7 @@ public class FunctionalInterfaceTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream() - .reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); @@ -178,10 +151,6 @@ public class FunctionalInterfaceTest { } - public double squareLazy(Supplier lazyValue) { - return Math.pow(lazyValue.get(), 2); - } - @Test public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() { @@ -196,4 +165,18 @@ public class FunctionalInterfaceTest { } + // + + public double squareLazy(Supplier lazyValue) { + return Math.pow(lazyValue.get(), 2); + } + + public byte[] transformArray(short[] array, ShortToByteFunction function) { + byte[] transformedArray = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + transformedArray[i] = function.applyAsByte(array[i]); + } + return transformedArray; + } + } 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/hexToAscii/HexToAscii.java b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java new file mode 100644 index 0000000000..2a3c4b109e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java @@ -0,0 +1,46 @@ +package com.baeldung.hexToAscii; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HexToAscii { + + @Test + public static void whenHexToAscii() { + String asciiString = "http://www.baeldung.com/jackson-serialize-dates"; + String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573"; + + assertEquals(asciiString, hexToAscii(hexEquivalent)); + } + + @Test + public static void whenAsciiToHex() { + String asciiString = "http://www.baeldung.com/jackson-serialize-dates"; + String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573"; + + assertEquals(hexEquivalent, asciiToHex(asciiString)); + } + + // + + private static String asciiToHex(String asciiStr) { + char[] chars = asciiStr.toCharArray(); + StringBuilder hex = new StringBuilder(); + for (char ch : chars) { + hex.append(Integer.toHexString((int) ch)); + } + + return hex.toString(); + } + + private static String hexToAscii(String hexStr) { + StringBuilder output = new StringBuilder(""); + for (int i = 0; i < hexStr.length(); i += 2) { + String str = hexStr.substring(i, i + 2); + output.append((char) Integer.parseInt(str, 16)); + } + return output.toString(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java new file mode 100644 index 0000000000..8635a24f18 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java @@ -0,0 +1,118 @@ +package com.baeldung.java.networking.interfaces; + +import org.junit.Test; + +import java.net.*; +import java.util.Enumeration; +import java.util.List; + +import static org.junit.Assert.*; + +public class NetworkInterfaceManualTest { + @Test + public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertNotNull(nif); + } + + @Test + public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException { + NetworkInterface nif = NetworkInterface.getByName("inexistent_name"); + assertNull(nif); + } + + @Test + public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { + byte[] ip = new byte[] { 127, 0, 0, 1 }; + NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip)); + assertNotNull(nif); + } + + @Test + public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost")); + assertNotNull(nif); + } + + @Test + public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); + assertNotNull(nif); + } + + @Test + public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress()); + assertNotNull(nif); + } + + @Test + public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByIndex(0); + assertNotNull(nif); + } + + @Test + public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + Enumeration addressEnum = nif.getInetAddresses(); + InetAddress address = addressEnum.nextElement(); + assertEquals("127.0.0.1", address.getHostAddress()); + } + + @Test + public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + + List addressEnum = nif.getInterfaceAddresses(); + InterfaceAddress address = addressEnum.get(0); + InetAddress localAddress = address.getAddress(); + InetAddress broadCastAddress = address.getBroadcast(); + assertEquals("127.0.0.1", localAddress.getHostAddress()); + assertEquals("127.255.255.255", broadCastAddress.getHostAddress()); + } + + @Test + public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertTrue(nif.isLoopback()); + } + + @Test + public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertTrue(nif.isUp()); + } + + @Test + public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertFalse(nif.isPointToPoint()); + } + + @Test + public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertFalse(nif.isVirtual()); + } + + @Test + public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + assertTrue(nif.supportsMulticast()); + } + + @Test + public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("lo"); + byte[] bytes = nif.getHardwareAddress(); + assertNotNull(bytes); + } + + @Test + public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException { + NetworkInterface nif = NetworkInterface.getByName("net0"); + int mtu = nif.getMTU(); + assertEquals(1500, mtu); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java new file mode 100644 index 0000000000..aff851ae4b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.java.networking.udp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class UDPIntegrationTest { + private EchoClient client; + + @Before + public void setup() throws IOException { + new EchoServer().start(); + client = new EchoClient(); + } + + @Test + public void whenCanSendAndReceivePacket_thenCorrect1() { + String echo = client.sendEcho("hello server"); + assertEquals("hello server", echo); + echo = client.sendEcho("server is working"); + assertFalse(echo.equals("hello server")); + } + + @After + public void tearDown() { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() { + client.sendEcho("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java new file mode 100644 index 0000000000..505d9595ab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java @@ -0,0 +1,104 @@ +package com.baeldung.java.networking.url; + +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Test; + +public class UrlUnitTest { + + @Test + public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals("http", url.getProtocol()); + } + + @Test + public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals("baeldung.com", url.getHost()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles?topic=java&version=8", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/guidelines.txt"); + assertEquals("/guidelines.txt", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles", url.getPath()); + } + + @Test + public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java"); + assertEquals("topic=java", url.getQuery()); + } + + @Test + public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals(-1, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com:8090"); + assertEquals(8090, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException { + final URL baseUrl = new URL("http://baeldung.com"); + final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException { + final URL baseUrl = new URL("http://baeldung.com"); + final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final String file = "/guidelines.txt"; + final URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/guidelines.txt", url.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final String file = "/articles?topic=java&version=8"; + final URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString()); + } + + @Test + public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final int port = 9000; + final String file = "/guidelines.txt"; + final URL url = new URL(protocol, host, port, file); + assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString()); + } + +} 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 deleted file mode 100644 index 63da2fe2bf..0000000000 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.java.nio.selector; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class EchoTest { - - @Test - public void givenClient_whenServerEchosMessage_thenCorrect() { - EchoClient client = EchoClient.start(); - String resp1 = client.sendMessage("hello"); - String resp2 = client.sendMessage("world"); - assertEquals("hello", resp1); - assertEquals("world", resp2); - } - -} diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java new file mode 100644 index 0000000000..fc64799578 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.java.nio.selector; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class NioEchoIntegrationTest { + + Process server; + EchoClient client; + + @Before + public void setup() throws IOException, InterruptedException { + server = EchoServer.start(); + client = EchoClient.start(); + } + + @Test + public void givenServerClient_whenServerEchosMessage_thenCorrect() { + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + assertEquals("hello", resp1); + assertEquals("world", resp2); + } + + @After + public void teardown() throws IOException { + server.destroy(); + EchoClient.stop(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java new file mode 100644 index 0000000000..64fbb4ae25 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java @@ -0,0 +1,246 @@ +package com.baeldung.java.nio2; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.UUID; + +import org.junit.Test; + +public class FileTest { + private static final String HOME = System.getProperty("user.home"); + + // checking file or dir + @Test + public void givenExistentPath_whenConfirmsFileExists_thenCorrect() { + Path p = Paths.get(HOME); + assertTrue(Files.exists(p)); + } + + @Test + public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() { + Path p = Paths.get(HOME + "/inexistent_file.txt"); + assertTrue(Files.notExists(p)); + } + + @Test + public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() { + Path p = Paths.get(HOME); + assertFalse(Files.isRegularFile(p)); + } + + @Test + public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() { + Path p = Paths.get(HOME); + assertTrue(Files.isReadable(p)); + } + + @Test + public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() { + Path p = Paths.get(HOME); + assertTrue(Files.isWritable(p)); + } + + @Test + public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() { + Path p = Paths.get(HOME); + assertTrue(Files.isExecutable(p)); + } + + @Test + public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException { + Path p1 = Paths.get(HOME); + Path p2 = Paths.get(HOME); + assertTrue(Files.isSameFile(p1, p2)); + } + + // reading, writing and creating files + // creating file + @Test + public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException { + String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt"; + Path p = Paths.get(HOME + "/" + fileName); + assertFalse(Files.exists(p)); + Files.createFile(p); + assertTrue(Files.exists(p)); + + } + + @Test + public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException { + String dirName = "myDir_" + UUID.randomUUID().toString(); + Path p = Paths.get(HOME + "/" + dirName); + assertFalse(Files.exists(p)); + Files.createDirectory(p); + assertTrue(Files.exists(p)); + assertFalse(Files.isRegularFile(p)); + assertTrue(Files.isDirectory(p)); + + } + + @Test(expected = NoSuchFileException.class) + public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException { + String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir"; + Path p = Paths.get(HOME + "/" + dirName); + assertFalse(Files.exists(p)); + Files.createDirectory(p); + + } + + @Test + public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException { + Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString()); + Path subdir = dir.resolve("subdir"); + assertFalse(Files.exists(dir)); + assertFalse(Files.exists(subdir)); + Files.createDirectories(subdir); + assertTrue(Files.exists(dir)); + assertTrue(Files.exists(subdir)); + } + + @Test + public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException { + String prefix = "log_"; + String suffix = ".txt"; + Path p = Paths.get(HOME + "/"); + p = Files.createTempFile(p, prefix, suffix); + // like log_8821081429012075286.txt + assertTrue(Files.exists(p)); + + } + + @Test + public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException { + Path p = Paths.get(HOME + "/"); + p = Files.createTempFile(p, null, null); + // like 8600179353689423985.tmp + assertTrue(Files.exists(p)); + } + + @Test + public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException { + Path p = Files.createTempFile(null, null); + // like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp + assertTrue(Files.exists(p)); + + } + + // delete file + @Test + public void givenPath_whenDeletes_thenCorrect() throws IOException { + Path p = Paths.get(HOME + "/fileToDelete.txt"); + assertFalse(Files.exists(p)); + Files.createFile(p); + assertTrue(Files.exists(p)); + Files.delete(p); + assertFalse(Files.exists(p)); + + } + + @Test(expected = DirectoryNotEmptyException.class) + public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException { + Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString()); + Files.createDirectory(dir); + assertTrue(Files.exists(dir)); + Path file = dir.resolve("file.txt"); + Files.createFile(file); + Files.delete(dir); + + assertTrue(Files.exists(dir)); + + } + + @Test(expected = NoSuchFileException.class) + public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException { + Path p = Paths.get(HOME + "/inexistentFile.txt"); + assertFalse(Files.exists(p)); + Files.delete(p); + + } + + @Test + public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException { + Path p = Paths.get(HOME + "/inexistentFile.txt"); + assertFalse(Files.exists(p)); + Files.deleteIfExists(p); + + } + + // copy file + @Test + public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException { + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Files.createDirectory(dir1); + Files.createDirectory(dir2); + Path file1 = dir1.resolve("filetocopy.txt"); + Path file2 = dir2.resolve("filetocopy.txt"); + Files.createFile(file1); + assertTrue(Files.exists(file1)); + assertFalse(Files.exists(file2)); + Files.copy(file1, file2); + assertTrue(Files.exists(file2)); + + } + + @Test(expected = FileAlreadyExistsException.class) + public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException { + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Files.createDirectory(dir1); + Files.createDirectory(dir2); + Path file1 = dir1.resolve("filetocopy.txt"); + Path file2 = dir2.resolve("filetocopy.txt"); + Files.createFile(file1); + Files.createFile(file2); + assertTrue(Files.exists(file1)); + assertTrue(Files.exists(file2)); + Files.copy(file1, file2); + Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING); + } + + // moving files + @Test + public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException { + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Files.createDirectory(dir1); + Files.createDirectory(dir2); + Path file1 = dir1.resolve("filetocopy.txt"); + Path file2 = dir2.resolve("filetocopy.txt"); + Files.createFile(file1); + assertTrue(Files.exists(file1)); + assertFalse(Files.exists(file2)); + Files.move(file1, file2); + assertTrue(Files.exists(file2)); + assertFalse(Files.exists(file1)); + + } + + @Test(expected = FileAlreadyExistsException.class) + public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException { + Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString()); + Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString()); + Files.createDirectory(dir1); + Files.createDirectory(dir2); + Path file1 = dir1.resolve("filetocopy.txt"); + Path file2 = dir2.resolve("filetocopy.txt"); + Files.createFile(file1); + Files.createFile(file2); + assertTrue(Files.exists(file1)); + assertTrue(Files.exists(file2)); + Files.move(file1, file2); + Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING); + assertTrue(Files.exists(file2)); + assertFalse(Files.exists(file1)); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java new file mode 100644 index 0000000000..acfb2c08e9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java @@ -0,0 +1,195 @@ +package com.baeldung.java.nio2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Date; + +import org.junit.Test; + +public class PathManualTest { + + private static final String HOME = System.getProperty("user.home"); + + // creating a path + @Test + public void givenPathString_whenCreatesPathObject_thenCorrect() { + Path p = Paths.get("/articles/baeldung"); + assertEquals("\\articles\\baeldung", p.toString()); + + } + + @Test + public void givenPathParts_whenCreatesPathObject_thenCorrect() { + Path p = Paths.get("/articles", "baeldung"); + assertEquals("\\articles\\baeldung", p.toString()); + + } + + // retrieving path info + @Test + public void givenPath_whenRetrievesFileName_thenCorrect() { + Path p = Paths.get("/articles/baeldung/logs"); + assertEquals("logs", p.getFileName().toString()); + } + + @Test + public void givenPath_whenRetrievesNameByIndex_thenCorrect() { + Path p = Paths.get("/articles/baeldung/logs"); + assertEquals("articles", p.getName(0).toString()); + assertEquals("baeldung", p.getName(1).toString()); + assertEquals("logs", p.getName(2).toString()); + } + + @Test + public void givenPath_whenCountsParts_thenCorrect() { + Path p = Paths.get("/articles/baeldung/logs"); + assertEquals(3, p.getNameCount()); + } + + @Test + public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() { + Path p = Paths.get("/articles/baeldung/logs"); + assertEquals("articles", p.subpath(0, 1).toString()); + assertEquals("articles\\baeldung", p.subpath(0, 2).toString()); + assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString()); + assertEquals("baeldung", p.subpath(1, 2).toString()); + assertEquals("baeldung\\logs", p.subpath(1, 3).toString()); + assertEquals("logs", p.subpath(2, 3).toString()); + } + + @Test + public void givenPath_whenRetrievesParent_thenCorrect() { + Path p1 = Paths.get("/articles/baeldung/logs"); + Path p2 = Paths.get("/articles/baeldung"); + Path p3 = Paths.get("/articles"); + Path p4 = Paths.get("/"); + + assertEquals("\\articles\\baeldung", p1.getParent().toString()); + assertEquals("\\articles", p2.getParent().toString()); + assertEquals("\\", p3.getParent().toString()); + assertEquals(null, p4.getParent()); + } + + @Test + public void givenPath_whenRetrievesRoot_thenCorrect() { + Path p1 = Paths.get("/articles/baeldung/logs"); + Path p2 = Paths.get("c:/articles/baeldung/logs"); + + assertEquals("\\", p1.getRoot().toString()); + assertEquals("c:\\", p2.getRoot().toString()); + } + + // removing redundancies from path + @Test + public void givenPath_whenRemovesRedundancies_thenCorrect1() { + Path p = Paths.get("/home/./baeldung/articles"); + p = p.normalize(); + assertEquals("\\home\\baeldung\\articles", p.toString()); + } + + @Test + public void givenPath_whenRemovesRedundancies_thenCorrect2() { + Path p = Paths.get("/home/baeldung/../articles"); + p = p.normalize(); + assertEquals("\\home\\articles", p.toString()); + } + + // converting a path + @Test + public void givenPath_whenConvertsToBrowseablePath_thenCorrect() { + Path p = Paths.get("/home/baeldung/articles.html"); + URI uri = p.toUri(); + assertEquals("file:///E:/home/baeldung/articles.html", uri.toString()); + } + + @Test + public void givenPath_whenConvertsToAbsolutePath_thenCorrect() { + Path p = Paths.get("/home/baeldung/articles.html"); + assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString()); + } + + @Test + public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() { + Path p = Paths.get("E:\\home\\baeldung\\articles.html"); + assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString()); + } + + @Test + public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException { + Path p = Paths.get(HOME); + assertEquals(HOME, p.toRealPath().toString()); + } + + @Test(expected = NoSuchFileException.class) + public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException { + Path p = Paths.get("E:\\home\\baeldung\\articles.html"); + + p.toRealPath(); + } + + // joining paths + @Test + public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException { + Path p = Paths.get("/baeldung/articles"); + assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString()); + } + + @Test + public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException { + Path p = Paths.get("/baeldung/articles"); + assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString()); + } + + @Test + public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException { + Path p = Paths.get("/baeldung/articles"); + assertEquals("\\java", p.resolve("/java").toString()); + } + + // creating a path between 2 paths + @Test + public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException { + Path p1 = Paths.get("articles"); + Path p2 = Paths.get("authors"); + assertEquals("..\\authors", p1.relativize(p2).toString()); + assertEquals("..\\articles", p2.relativize(p1).toString()); + } + + @Test + public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException { + Path p1 = Paths.get("/baeldung"); + Path p2 = Paths.get("/baeldung/authors/articles"); + assertEquals("authors\\articles", p1.relativize(p2).toString()); + assertEquals("..\\..", p2.relativize(p1).toString()); + } + + // comparing 2 paths + @Test + public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException { + Path p1 = Paths.get("/baeldung/articles"); + Path p2 = Paths.get("/baeldung/articles"); + Path p3 = Paths.get("/baeldung/authors"); + + assertTrue(p1.equals(p2)); + assertFalse(p1.equals(p3)); + } + + @Test + public void givenPath_whenInspectsStart_thenCorrect() { + Path p1 = Paths.get("/baeldung/articles"); + assertTrue(p1.startsWith("/baeldung")); + } + + @Test + public void givenPath_whenInspectsEnd_thenCorrect() { + Path p1 = Paths.get("/baeldung/articles"); + assertTrue(p1.endsWith("articles")); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java deleted file mode 100644 index a12a2f205f..0000000000 --- a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java +++ /dev/null @@ -1,326 +0,0 @@ -package com.baeldung.java.reflection; - -import org.junit.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import static org.junit.Assert.*; - -public class ReflectionTest { - - @Test - public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { - Object person = new Person(); - Field[] fields = person.getClass().getDeclaredFields(); - - List actualFieldNames = getFieldNames(fields); - - assertTrue(Arrays.asList("name", "age") - .containsAll(actualFieldNames)); - } - - @Test - public void givenObject_whenGetsClassName_thenCorrect() { - Object goat = new Goat("goat"); - Class clazz = goat.getClass(); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClassName_whenCreatesObject_thenCorrect() - throws ClassNotFoundException { - Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClass_whenRecognisesModifiers_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - int goatMods = goatClass.getModifiers(); - int animalMods = animalClass.getModifiers(); - - assertTrue(Modifier.isPublic(goatMods)); - assertTrue(Modifier.isAbstract(animalMods)); - assertTrue(Modifier.isPublic(animalMods)); - } - - @Test - public void givenClass_whenGetsPackageInfo_thenCorrect() { - Goat goat = new Goat("goat"); - Class goatClass = goat.getClass(); - Package pkg = goatClass.getPackage(); - - assertEquals("com.baeldung.java.reflection", pkg.getName()); - } - - @Test - public void givenClass_whenGetsSuperClass_thenCorrect() { - Goat goat = new Goat("goat"); - String str = "any string"; - - Class goatClass = goat.getClass(); - Class goatSuperClass = goatClass.getSuperclass(); - - assertEquals("Animal", goatSuperClass.getSimpleName()); - assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); - - } - - @Test - public void givenClass_whenGetsImplementedInterfaces_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Class[] goatInterfaces = goatClass.getInterfaces(); - Class[] animalInterfaces = animalClass.getInterfaces(); - - assertEquals(1, goatInterfaces.length); - assertEquals(1, animalInterfaces.length); - assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); - assertEquals("Eating", animalInterfaces[0].getSimpleName()); - } - - @Test - public void givenClass_whenGetsConstructor_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Constructor[] constructors = goatClass.getConstructors(); - - assertEquals(1, constructors.length); - assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); - } - - @Test - public void givenClass_whenGetsFields_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Field[] fields = animalClass.getDeclaredFields(); - - List actualFields = getFieldNames(fields); - - assertEquals(2, actualFields.size()); - assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); - } - - @Test - public void givenClass_whenGetsMethods_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Method[] methods = animalClass.getDeclaredMethods(); - List actualMethods = getMethodNames(methods); - - assertEquals(4, actualMethods.size()); - assertTrue(actualMethods.containsAll(Arrays.asList("getName", - "setName", "getSound"))); - } - - @Test - public void givenClass_whenGetsAllConstructors_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Constructor[] constructors = birdClass.getConstructors(); - - assertEquals(3, constructors.length); - } - - @Test - public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - } - - @Test - public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - - Bird bird1 = (Bird) cons1.newInstance(); - Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); - Bird bird3 = (Bird) cons3.newInstance("dove", true); - - assertEquals("bird", bird1.getName()); - assertEquals("Weaver bird", bird2.getName()); - assertEquals("dove", bird3.getName()); - assertFalse(bird1.walks()); - assertTrue(bird3.walks()); - } - - @Test - public void givenClass_whenGetsPublicFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field[] fields = birdClass.getFields(); - assertEquals(1, fields.length); - assertEquals("CATEGORY", fields[0].getName()); - - } - - @Test - public void givenClass_whenGetsPublicFieldByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - assertEquals("CATEGORY", field.getName()); - - } - - @Test - public void givenClass_whenGetsDeclaredFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field[] fields = birdClass.getDeclaredFields(); - assertEquals(1, fields.length); - assertEquals("walks", fields[0].getName()); - } - - @Test - public void givenClass_whenGetsFieldsByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getDeclaredField("walks"); - assertEquals("walks", field.getName()); - - } - - @Test - public void givenClassField_whenGetsType_thenCorrect() - throws Exception { - Field field = Class.forName("com.baeldung.java.reflection.Bird") - .getDeclaredField("walks"); - Class fieldClass = field.getType(); - assertEquals("boolean", fieldClass.getSimpleName()); - } - - @Test - public void givenClassField_whenSetsAndGetsValue_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Field field = birdClass.getDeclaredField("walks"); - field.setAccessible(true); - - assertFalse(field.getBoolean(bird)); - assertFalse(bird.walks()); - - field.set(bird, true); - - assertTrue(field.getBoolean(bird)); - assertTrue(bird.walks()); - - } - - @Test - public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - field.setAccessible(true); - - assertEquals("domestic", field.get(null)); - } - - @Test - public void givenClass_whenGetsAllPublicMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Method[] methods = birdClass.getMethods(); - List methodNames = getMethodNames(methods); - - assertTrue(methodNames.containsAll(Arrays - .asList("equals", "notifyAll", "hashCode", - "walks", "eats", "toString"))); - - } - - @Test - public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); - - List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); - - assertEquals(expectedMethodNames.size(), actualMethodNames.size()); - assertTrue(expectedMethodNames.containsAll(actualMethodNames)); - assertTrue(actualMethodNames.containsAll(expectedMethodNames)); - - } - - @Test - public void givenMethodName_whenGetsMethod_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - - assertFalse(walksMethod.isAccessible()); - assertFalse(setWalksMethod.isAccessible()); - - walksMethod.setAccessible(true); - setWalksMethod.setAccessible(true); - - assertTrue(walksMethod.isAccessible()); - assertTrue(setWalksMethod.isAccessible()); - - } - - @Test - public void givenMethod_whenInvokes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - boolean walks = (boolean) walksMethod.invoke(bird); - - assertFalse(walks); - assertFalse(bird.walks()); - - setWalksMethod.invoke(bird, true); - boolean walks2 = (boolean) walksMethod.invoke(bird); - - assertTrue(walks2); - assertTrue(bird.walks()); - - } - - private static List getFieldNames(Field[] fields) { - List fieldNames = new ArrayList<>(); - for (Field field : fields) - fieldNames.add(field.getName()); - return fieldNames; - - } - - private static List getMethodNames(Method[] methods) { - List methodNames = new ArrayList<>(); - for (Method method : methods) - methodNames.add(method.getName()); - return methodNames; - } - -} diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java new file mode 100644 index 0000000000..0c090901e7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java @@ -0,0 +1,302 @@ +package com.baeldung.java.reflection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class ReflectionUnitTest { + + @Test + public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { + final Object person = new Person(); + final Field[] fields = person.getClass().getDeclaredFields(); + + final List actualFieldNames = getFieldNames(fields); + + assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames)); + } + + @Test + public void givenObject_whenGetsClassName_thenCorrect() { + final Object goat = new Goat("goat"); + final Class clazz = goat.getClass(); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException { + final Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final int goatMods = goatClass.getModifiers(); + final int animalMods = animalClass.getModifiers(); + + assertTrue(Modifier.isPublic(goatMods)); + assertTrue(Modifier.isAbstract(animalMods)); + assertTrue(Modifier.isPublic(animalMods)); + } + + @Test + public void givenClass_whenGetsPackageInfo_thenCorrect() { + final Goat goat = new Goat("goat"); + final Class goatClass = goat.getClass(); + final Package pkg = goatClass.getPackage(); + + assertEquals("com.baeldung.java.reflection", pkg.getName()); + } + + @Test + public void givenClass_whenGetsSuperClass_thenCorrect() { + final Goat goat = new Goat("goat"); + final String str = "any string"; + + final Class goatClass = goat.getClass(); + final Class goatSuperClass = goatClass.getSuperclass(); + + assertEquals("Animal", goatSuperClass.getSimpleName()); + assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); + + } + + @Test + public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Class[] goatInterfaces = goatClass.getInterfaces(); + final Class[] animalInterfaces = animalClass.getInterfaces(); + + assertEquals(1, goatInterfaces.length); + assertEquals(1, animalInterfaces.length); + assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); + assertEquals("Eating", animalInterfaces[0].getSimpleName()); + } + + @Test + public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Constructor[] constructors = goatClass.getConstructors(); + + assertEquals(1, constructors.length); + assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); + } + + @Test + public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException { + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Field[] fields = animalClass.getDeclaredFields(); + + final List actualFields = getFieldNames(fields); + + assertEquals(2, actualFields.size()); + assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); + } + + @Test + public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException { + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Method[] methods = animalClass.getDeclaredMethods(); + final List actualMethods = getMethodNames(methods); + + assertEquals(3, actualMethods.size()); + assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound"))); + } + + @Test + public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Constructor[] constructors = birdClass.getConstructors(); + + assertEquals(3, constructors.length); + } + + @Test + public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + birdClass.getConstructor(); + birdClass.getConstructor(String.class); + birdClass.getConstructor(String.class, boolean.class); + } + + @Test + public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + + final Constructor cons1 = birdClass.getConstructor(); + final Constructor cons2 = birdClass.getConstructor(String.class); + final Constructor cons3 = birdClass.getConstructor(String.class, boolean.class); + + final Bird bird1 = (Bird) cons1.newInstance(); + final Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); + final Bird bird3 = (Bird) cons3.newInstance("dove", true); + + assertEquals("bird", bird1.getName()); + assertEquals("Weaver bird", bird2.getName()); + assertEquals("dove", bird3.getName()); + assertFalse(bird1.walks()); + assertTrue(bird3.walks()); + } + + @Test + public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field[] fields = birdClass.getFields(); + assertEquals(1, fields.length); + assertEquals("CATEGORY", fields[0].getName()); + + } + + @Test + public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getField("CATEGORY"); + assertEquals("CATEGORY", field.getName()); + + } + + @Test + public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field[] fields = birdClass.getDeclaredFields(); + assertEquals(1, fields.length); + assertEquals("walks", fields[0].getName()); + } + + @Test + public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getDeclaredField("walks"); + assertEquals("walks", field.getName()); + + } + + @Test + public void givenClassField_whenGetsType_thenCorrect() throws Exception { + final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks"); + final Class fieldClass = field.getType(); + assertEquals("boolean", fieldClass.getSimpleName()); + } + + @Test + public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Bird bird = (Bird) birdClass.newInstance(); + final Field field = birdClass.getDeclaredField("walks"); + field.setAccessible(true); + + assertFalse(field.getBoolean(bird)); + assertFalse(bird.walks()); + + field.set(bird, true); + + assertTrue(field.getBoolean(bird)); + assertTrue(bird.walks()); + + } + + @Test + public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getField("CATEGORY"); + field.setAccessible(true); + + assertEquals("domestic", field.get(null)); + } + + @Test + public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Method[] methods = birdClass.getMethods(); + final List methodNames = getMethodNames(methods); + + assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString"))); + + } + + @Test + public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); + + final List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); + + assertEquals(expectedMethodNames.size(), actualMethodNames.size()); + assertTrue(expectedMethodNames.containsAll(actualMethodNames)); + assertTrue(actualMethodNames.containsAll(expectedMethodNames)); + + } + + @Test + public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Method walksMethod = birdClass.getDeclaredMethod("walks"); + final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); + + assertFalse(walksMethod.isAccessible()); + assertFalse(setWalksMethod.isAccessible()); + + walksMethod.setAccessible(true); + setWalksMethod.setAccessible(true); + + assertTrue(walksMethod.isAccessible()); + assertTrue(setWalksMethod.isAccessible()); + + } + + @Test + public void givenMethod_whenInvokes_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Bird bird = (Bird) birdClass.newInstance(); + final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); + final Method walksMethod = birdClass.getDeclaredMethod("walks"); + final boolean walks = (boolean) walksMethod.invoke(bird); + + assertFalse(walks); + assertFalse(bird.walks()); + + setWalksMethod.invoke(bird, true); + final boolean walks2 = (boolean) walksMethod.invoke(bird); + + assertTrue(walks2); + assertTrue(bird.walks()); + + } + + private static List getFieldNames(Field[] fields) { + final List fieldNames = new ArrayList<>(); + for (final Field field : fields) { + fieldNames.add(field.getName()); + } + return fieldNames; + + } + + private static List getMethodNames(Method[] methods) { + final List methodNames = new ArrayList<>(); + for (final Method method : methods) { + methodNames.add(method.getName()); + } + return methodNames; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/regex/RegexTest.java rename to core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java index 414401eb85..e4ea55aae3 100644 --- a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java @@ -7,7 +7,7 @@ import java.util.regex.Pattern; import org.junit.Test; -public class RegexTest { +public class RegexUnitTest { private static Pattern pattern; private static Matcher matcher; @@ -499,4 +499,3 @@ public class RegexTest { return matches; } } - diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java index 21a5e34b9b..5b07b3e3ae 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class Java8DefaultStaticIntefaceMethodsTest { +public class Java8DefaultStaticIntefaceMethodsUnitTest { @Test public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java similarity index 83% rename from core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java index 581ccec182..41eb864fd9 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java @@ -1,17 +1,26 @@ package com.baeldung.java8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; - -import static org.junit.Assert.*; - - -public class Java8ExecutorServiceTest { +public class Java8ExecutorServiceIntegrationTest { private Runnable runnableTask; private Callable callableTask; @@ -53,9 +62,7 @@ public class Java8ExecutorServiceTest { @Test public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() { - ExecutorService threadPoolExecutor = - new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>()); + ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); for (int i = 0; i < 100; i++) { threadPoolExecutor.submit(callableTask); @@ -138,8 +145,7 @@ public class Java8ExecutorServiceTest { @Test public void submittingTaskScheduling_whenExecuted_thenCorrect() { - ScheduledExecutorService executorService = Executors - .newSingleThreadScheduledExecutor(); + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS); String result = null; diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java new file mode 100644 index 0000000000..d9b0aa9d98 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java @@ -0,0 +1,52 @@ +package com.baeldung.java8; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import org.junit.Test; + +public class Java8ForEachTest { + + @Test + public void compareForEachMethods_thenPrintResults() { + + List names = new ArrayList<>(); + names.add("Larry"); + names.add("Steve"); + names.add("James"); + names.add("Conan"); + names.add("Ellen"); + + // Java 5 - for-loop + System.out.println("--- Enhanced for-loop ---"); + for (String name : names) { + System.out.println(name); + } + + // Java 8 - forEach + System.out.println("--- forEach method ---"); + names.forEach(name -> System.out.println(name)); + + // Anonymous inner class that implements Consumer interface + System.out.println("--- Anonymous inner class ---"); + names.forEach(new Consumer() { + public void accept(String name) { + System.out.println(name); + } + }); + + // Create a Consumer implementation to then use in a forEach method + Consumer consumerNames = name -> { + System.out.println(name); + }; + System.out.println("--- Implementation of Consumer interface ---"); + names.forEach(consumerNames); + + // Print elements using a Method Reference + System.out.println("--- Method Reference ---"); + names.forEach(System.out::println); + + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java similarity index 94% rename from core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java index 273b2d78db..6778fd782b 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java @@ -1,18 +1,20 @@ package com.baeldung.java8; - -import com.baeldung.forkjoin.CustomRecursiveAction; -import com.baeldung.forkjoin.CustomRecursiveTask; -import com.baeldung.forkjoin.util.PoolUtil; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Random; import java.util.concurrent.ForkJoinPool; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; -public class Java8ForkJoinTest { +import com.baeldung.forkjoin.CustomRecursiveAction; +import com.baeldung.forkjoin.CustomRecursiveTask; +import com.baeldung.forkjoin.util.PoolUtil; + +public class Java8ForkJoinIntegrationTest { private int[] arr; private CustomRecursiveTask customRecursiveTask; @@ -27,28 +29,23 @@ public class Java8ForkJoinTest { customRecursiveTask = new CustomRecursiveTask(arr); } - @Test public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() { - ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool; ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool; assertNotNull(forkJoinPool); assertEquals(2, forkJoinPool.getParallelism()); assertEquals(forkJoinPool, forkJoinPoolTwo); - } @Test public void callCommonPool_whenExistsAndExpectedType_thenCorrect() { - ForkJoinPool commonPool = ForkJoinPool.commonPool(); ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool(); assertNotNull(commonPool); assertEquals(commonPool, commonPoolTwo); - } @Test @@ -63,7 +60,6 @@ public class Java8ForkJoinTest { @Test public void executeRecursiveTask_whenExecuted_thenCorrect() { - ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); forkJoinPool.execute(customRecursiveTask); @@ -73,12 +69,10 @@ public class Java8ForkJoinTest { forkJoinPool.submit(customRecursiveTask); int resultTwo = customRecursiveTask.join(); assertTrue(customRecursiveTask.isDone()); - } @Test public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() { - CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr); CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr); CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr); @@ -95,6 +89,6 @@ public class Java8ForkJoinTest { assertTrue(customRecursiveTaskSecond.isDone()); assertTrue(customRecursiveTaskLast.isDone()); assertTrue(result != 0); - } + } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java index faaf3ae407..13ddcc805f 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java @@ -11,7 +11,7 @@ import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class Java8FunctionalInteracesLambdasTest { +public class Java8FunctionalInteracesLambdasUnitTest { private UseFoo useFoo; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java index d9d88c5052..2dc1fe18e6 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java @@ -12,7 +12,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class Java8MethodReferenceTest { +public class Java8MethodReferenceUnitTest { private List list; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java similarity index 80% rename from core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java index 26de39bc0e..c6d5836387 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java @@ -1,16 +1,23 @@ package com.baeldung.java8; -import com.baeldung.java_8_features.*; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; -public class Java8OptionalTest { +import com.baeldung.java_8_features.Address; +import com.baeldung.java_8_features.CustomException; +import com.baeldung.java_8_features.OptionalAddress; +import com.baeldung.java_8_features.OptionalUser; +import com.baeldung.java_8_features.User; + +public class Java8OptionalUnitTest { private List list; @@ -32,7 +39,6 @@ public class Java8OptionalTest { @Test public void checkOptional_whenAsExpected_thenCorrect() { - Optional optionalEmpty = Optional.empty(); assertFalse(optionalEmpty.isPresent()); @@ -52,27 +58,19 @@ public class Java8OptionalTest { assertTrue(listOptNull.isEmpty()); Optional user = Optional.ofNullable(getUser()); - String result = user.map(User::getAddress) - .map(Address::getStreet) - .orElse("not specified"); + String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified"); assertEquals(result, "1st Avenue"); Optional optionalUser = Optional.ofNullable(getOptionalUser()); - String resultOpt = optionalUser.flatMap(OptionalUser::getAddress) - .flatMap(OptionalAddress::getStreet) - .orElse("not specified"); + String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified"); assertEquals(resultOpt, "1st Avenue"); Optional userNull = Optional.ofNullable(getUserNull()); - String resultNull = userNull.map(User::getAddress) - .map(Address::getStreet) - .orElse("not specified"); + String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified"); assertEquals(resultNull, "not specified"); Optional optionalUserNull = Optional.ofNullable(getOptionalUserNull()); - String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress) - .flatMap(OptionalAddress::getStreet) - .orElse("not specified"); + String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified"); assertEquals(resultOptNull, "not specified"); } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java similarity index 71% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java index 37326c6d26..73a10a57f4 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java @@ -17,28 +17,24 @@ import java.util.stream.*; import static org.junit.Assert.*; -public class Java8StreamApiTest { +public class Java8StreamApiUnitTest { private long counter; - private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class); + private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class); private List productList; @Before public void init() { - productList = Arrays.asList( - new Product(23, "potatoes"), new Product(14, "orange"), - new Product(13, "lemon"), new Product(23, "bread"), - new Product(13, "sugar")); + productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar")); } @Test public void checkPipeline_whenStreamOneElementShorter_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - long size = list.stream().skip(1) - .map(element -> element.substring(0, 3)).count(); + long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count(); assertEquals(list.size() - 1, size); } @@ -48,11 +44,10 @@ public class Java8StreamApiTest { List list = Arrays.asList("abc1", "abc2", "abc3"); counter = 0; - long sizeFirst = list.stream() - .skip(2).map(element -> { - wasCalled(); - return element.substring(0, 3); - }).count(); + long sizeFirst = list.stream().skip(2).map(element -> { + wasCalled(); + return element.substring(0, 3); + }).count(); assertEquals(1, counter); counter = 0; @@ -84,7 +79,7 @@ public class Java8StreamApiTest { Stream streamOfArray = Stream.of("a", "b", "c"); assertEquals(3, streamOfArray.count()); - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamOfArrayPart = Arrays.stream(arr, 1, 3); assertEquals(2, streamOfArrayPart.count()); @@ -112,7 +107,7 @@ public class Java8StreamApiTest { } assertEquals("a", streamOfStrings.findFirst().get()); - Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build(); + Stream streamBuilder = Stream. builder().add("a").add("b").add("c").build(); assertEquals(3, streamBuilder.count()); Stream streamGenerated = Stream.generate(() -> "element").limit(10); @@ -126,14 +121,13 @@ public class Java8StreamApiTest { public void runStreamPipeline_whenOrderIsRight_thenCorrect() { List list = Arrays.asList("abc1", "abc2", "abc3"); - Optional stream = list.stream() - .filter(element -> { - log.info("filter() was called"); - return element.contains("2"); - }).map(element -> { - log.info("map() was called"); - return element.toUpperCase(); - }).findFirst(); + Optional stream = list.stream().filter(element -> { + log.info("filter() was called"); + return element.contains("2"); + }).map(element -> { + log.info("map() was called"); + return element.toUpperCase(); + }).findFirst(); } @Test @@ -145,32 +139,28 @@ public class Java8StreamApiTest { int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b); assertEquals(16, reducedTwoParams); - int reducedThreeParams = Stream.of(1, 2, 3) - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(16, reducedThreeParams); - int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream() - .reduce(10, (a, b) -> a + b, (a, b) -> { - log.info("combiner was called"); - return a + b; - }); + int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> { + log.info("combiner was called"); + return a + b; + }); assertEquals(36, reducedThreeParamsParallel); } @Test public void collecting_whenAsExpected_thenCorrect() { - List collectorCollection = productList.stream() - .map(Product::getName).collect(Collectors.toList()); + List collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList()); assertTrue(collectorCollection instanceof List); assertEquals(5, collectorCollection.size()); - String listToString = productList.stream().map(Product::getName) - .collect(Collectors.joining(", ", "[", "]")); + String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]")); assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]")); @@ -180,36 +170,29 @@ public class Java8StreamApiTest { int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice)); assertEquals(86, summingPrice); - IntSummaryStatistics statistics = productList.stream() - .collect(Collectors.summarizingInt(Product::getPrice)); + IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice)); assertEquals(23, statistics.getMax()); - Map> collectorMapOfLists = productList.stream() - .collect(Collectors.groupingBy(Product::getPrice)); + Map> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice)); assertEquals(3, collectorMapOfLists.keySet().size()); - Map> mapPartioned = productList.stream() - .collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); + Map> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15)); assertEquals(2, mapPartioned.keySet().size()); } @Test(expected = UnsupportedOperationException.class) public void collect_whenThrows_thenCorrect() { - Set unmodifiableSet = productList.stream() - .collect(Collectors.collectingAndThen(Collectors.toSet(), - Collections::unmodifiableSet)); + Set unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); unmodifiableSet.add(new Product(4, "tea")); } @Test public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() { - Collector> toLinkedList = - Collector.of(LinkedList::new, LinkedList::add, - (first, second) -> { - first.addAll(second); - return first; - }); + Collector> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> { + first.addAll(second); + return first; + }); LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList); assertTrue(linkedListOfPersons.containsAll(productList)); @@ -219,23 +202,20 @@ public class Java8StreamApiTest { public void parallelStream_whenWorks_thenCorrect() { Stream streamOfCollection = productList.parallelStream(); boolean isParallel = streamOfCollection.isParallel(); - boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12) - .anyMatch(price -> price > 200); + boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200); assertTrue(isParallel && haveBigPrice); } @Test public void parallel_whenIsParallel_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); boolean isParallel = intStreamParallel.isParallel(); assertTrue(isParallel); } @Test public void parallel_whenIsSequential_thenCorrect() { - IntStream intStreamParallel = - IntStream.range(1, 150).parallel().map(element -> element * 34); + IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34); IntStream intStreamSequential = intStreamParallel.sequential(); boolean isParallel = intStreamParallel.isParallel(); assertFalse(isParallel); diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java similarity index 87% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java index 1f1dda49ce..e40f9f9506 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java @@ -14,7 +14,7 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -public class Java8StreamsTest { +public class Java8StreamsUnitTest { private List list; @@ -36,7 +36,7 @@ public class Java8StreamsTest { @Test public void checkStreamCount_whenCreating_givenDifferentSources() { - String[] arr = new String[]{"a", "b", "c"}; + String[] arr = new String[] { "a", "b", "c" }; Stream streamArr = Arrays.stream(arr); assertEquals(streamArr.count(), 3); @@ -47,14 +47,12 @@ public class Java8StreamsTest { assertEquals(count, 9); } - @Test public void checkStreamCount_whenOperationFilter_thanCorrect() { Stream streamFilter = list.stream().filter(element -> element.isEmpty()); assertEquals(streamFilter.count(), 2); } - @Test public void checkStreamCount_whenOperationMap_thanCorrect() { List uris = new ArrayList<>(); @@ -65,12 +63,10 @@ public class Java8StreamsTest { List details = new ArrayList<>(); details.add(new Detail()); details.add(new Detail()); - Stream streamFlatMap = details.stream() - .flatMap(detail -> detail.getParts().stream()); + Stream streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream()); assertEquals(streamFlatMap.count(), 4); } - @Test public void checkStreamCount_whenOperationMatch_thenCorrect() { boolean isValid = list.stream().anyMatch(element -> element.contains("h")); @@ -81,7 +77,6 @@ public class Java8StreamsTest { assertFalse(isValidTwo); } - @Test public void checkStreamReducedValue_whenOperationReduce_thenCorrect() { List integers = new ArrayList<>(); @@ -94,20 +89,17 @@ public class Java8StreamsTest { @Test public void checkStreamContains_whenOperationCollect_thenCorrect() { - List resultList = list.stream() - .map(element -> element.toUpperCase()) - .collect(Collectors.toList()); + List resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList()); assertEquals(resultList.size(), list.size()); assertTrue(resultList.contains("")); } - @Test public void checkParallelStream_whenDoWork() { list.parallelStream().forEach(element -> doWork(element)); } private void doWork(String string) { - assertTrue(true); //just imitate an amount of work + assertTrue(true); // just imitate an amount of work } } diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java similarity index 76% rename from core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java rename to core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index f2e7452137..1f3b380772 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -1,43 +1,43 @@ package com.baeldung.java8; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; -import java.nio.file.*; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.text.DecimalFormat; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; -import static org.junit.Assert.assertEquals; - -public class JavaFolderSizeTest { +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +public class JavaFolderSizeUnitTest { + private final long EXPECTED_SIZE = 24; private String path; @Before public void init() { final String separator = File.separator; - path = String.format("src%stest%sresources", separator, separator); + path = String.format("src%stest%sresources%stestFolder", separator, separator, separator); } @Test public void whenGetFolderSizeRecursive_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final long size = getFolderSize(folder); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException { - final long expectedSize = 136; - final AtomicLong size = new AtomicLong(0); final Path folder = Paths.get(path); @@ -49,41 +49,33 @@ public class JavaFolderSizeTest { } }); - assertEquals(expectedSize, size.longValue()); + assertEquals(EXPECTED_SIZE, size.longValue()); } @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { - final long expectedSize = 136; - final Path folder = Paths.get(path); final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final long size = FileUtils.sizeOfDirectory(folder); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingGuava_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false) - .filter(File::isFile) - .mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test @@ -91,19 +83,19 @@ public class JavaFolderSizeTest { final File folder = new File(path); final long size = getFolderSize(folder); - final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"}; + final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; final int unitIndex = (int) (Math.log10(size) / 3); final double unitValue = 1 << (unitIndex * 10); final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex]; - assertEquals("136 B", readableSize); + assertEquals(EXPECTED_SIZE + " B", readableSize); } private long getFolderSize(final File folder) { long length = 0; final File[] files = folder.listFiles(); - for (File file : files) { + for (final File file : files) { if (file.isFile()) { length += file.length(); } else { diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java rename to core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java index 224c4e9d6a..4c843ccaaf 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java @@ -8,7 +8,7 @@ import java.io.StringWriter; import java.util.Date; import java.util.Scanner; -public class JavaTryWithResourcesTest { +public class JavaTryWithResourcesUnitTest { private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private Date resource1Date, resource2Date; diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java rename to core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java index 164a571817..7889e6ad53 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java @@ -7,7 +7,7 @@ import java.io.UnsupportedEncodingException; import static org.junit.Assert.*; -public class ApacheCommonsEncodeDecodeTest { +public class ApacheCommonsEncodeDecodeUnitTest { // tests diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java rename to core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java index 18dccf71ba..62cfa4c0a1 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java @@ -8,7 +8,7 @@ import java.util.UUID; import static org.junit.Assert.*; -public class Java8EncodeDecodeTest { +public class Java8EncodeDecodeUnitTest { // tests diff --git a/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java b/core-java/src/test/java/com/baeldung/java8/entity/Human.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/entity/Human.java rename to core-java/src/test/java/com/baeldung/java8/entity/Human.java diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java new file mode 100644 index 0000000000..13609b6977 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.printscreen; + +import org.junit.After; +import org.junit.Test; + +import java.io.File; + +import static org.junit.Assert.assertTrue; + +public class ScreenshotIntegrationTest { + + 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/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java new file mode 100644 index 0000000000..7ac8e0a97a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.socket; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.Executors; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class EchoIntegrationTest { + private static final Integer PORT = 4444; + + @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", PORT); + } + + @After + public void tearDown() { + client.stopConnection(); + } + + // + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + String resp3 = client.sendMessage("!"); + String resp4 = client.sendMessage("."); + assertEquals("hello", resp1); + assertEquals("world", resp2); + assertEquals("!", resp3); + assertEquals("good bye", resp4); + } + +} diff --git a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java similarity index 65% rename from sockets/src/test/java/com/baeldung/socket/GreetServerTest.java rename to core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index fedc32fb39..06b37d8539 100644 --- a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -2,24 +2,29 @@ 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; import static org.junit.Assert.assertEquals; -public class GreetServerTest { +public class GreetServerIntegrationTest { - 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/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java new file mode 100644 index 0000000000..6ebc0946c5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java @@ -0,0 +1,59 @@ +package com.baeldung.socket; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +public class SocketEchoMultiIntegrationTest { + + 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", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + + @Test + public void givenClient2_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + 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"); + client.stopConnection(); + } + + @Test + public void givenClient3_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + 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"); + client.stopConnection(); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java similarity index 86% rename from core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java rename to core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index df336f4a93..a62ec99043 100644 --- a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -1,13 +1,23 @@ package com.baeldung.threadpool; -import java.util.concurrent.*; +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class CoreThreadPoolTest { +public class CoreThreadPoolIntegrationTest { @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { @@ -132,9 +142,7 @@ public class CoreThreadPoolTest { @Test public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() { - TreeNode tree = new TreeNode(5, - new TreeNode(3), new TreeNode(2, - new TreeNode(2), new TreeNode(8))); + TreeNode tree = new TreeNode(5, new TreeNode(3), new TreeNode(2, new TreeNode(2), new TreeNode(8))); ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); int sum = forkJoinPool.invoke(new CountingTask(tree)); @@ -142,5 +150,4 @@ public class CoreThreadPoolTest { assertEquals(20, sum); } - } diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java rename to core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java index 92e0f9a8cb..550e9dda6f 100644 --- a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class GuavaThreadPoolTest { +public class GuavaThreadPoolIntegrationTest { @Test public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() { @@ -46,9 +46,7 @@ public class GuavaThreadPoolTest { ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello"); ListenableFuture future2 = listeningExecutorService.submit(() -> "World"); - String greeting = Futures.allAsList(future1, future2).get() - .stream() - .collect(Collectors.joining(" ")); + String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" ")); assertEquals("Hello World", greeting); } diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java similarity index 85% rename from core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java rename to core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index da9027060e..3ad3deb548 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,41 +1,43 @@ -package com.baeldung.util; - -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(clock); - - 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(clock); - - 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(clock); - - assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); - } -} +package com.baeldung.util; + +import static org.junit.Assert.assertEquals; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.temporal.ChronoField; + +import org.junit.Test; + +public class CurrentDateTimeUnitTest { + + 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(clock); + + 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(clock); + + 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(clock); + + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java similarity index 87% rename from core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java rename to core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java index 23be2200d3..e615e6a7d1 100644 --- a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java @@ -1,13 +1,17 @@ package org.baeldung.core.exceptions; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + import org.apache.log4j.Logger; import org.junit.Test; -import java.io.*; +public class FileNotFoundExceptionUnitTest { -public class FileNotFoundExceptionTest { - - private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class); + private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class); private String fileName = Double.toString(Math.random()); @@ -42,7 +46,7 @@ public class FileNotFoundExceptionTest { LOG.error("Optional file " + fileName + " was not found.", ex); } } - + private void readFailingFile() throws IOException { BufferedReader rd = new BufferedReader(new FileReader(new File(fileName))); rd.readLine(); diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java similarity index 79% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java index 75d96e5989..680a6d57b5 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java @@ -2,22 +2,24 @@ package org.baeldung.equalshashcode.entities; import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import org.junit.Assert; import org.junit.Test; -public class ComplexClassTest { +import com.baeldung.equalshashcode.entities.ComplexClass; + +public class ComplexClassUnitTest { @Test public void testEqualsAndHashcodes() { - - ArrayList strArrayList = new ArrayList(); + List strArrayList = new ArrayList(); strArrayList.add("abc"); strArrayList.add("def"); ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45, 67)); ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45, 67)); - ArrayList strArrayListD = new ArrayList(); + List strArrayListD = new ArrayList(); strArrayListD.add("lmn"); strArrayListD.add("pqr"); ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45, 67)); diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java similarity index 86% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java index 16f25ae021..f4e9f2b99f 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java @@ -3,7 +3,9 @@ package org.baeldung.equalshashcode.entities; import org.junit.Assert; import org.junit.Test; -public class PrimitiveClassTest { +import com.baeldung.equalshashcode.entities.PrimitiveClass; + +public class PrimitiveClassUnitTest { @Test public void testTwoEqualsObjects() { diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java similarity index 87% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java index 52d024a696..5c860bd62d 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java @@ -5,11 +5,12 @@ import java.awt.Color; import org.junit.Assert; import org.junit.Test; -public class SquareClassTest { +import com.baeldung.equalshashcode.entities.Square; + +public class SquareClassUnitTest { @Test public void testEqualsAndHashcodes() { - Square aObject = new Square(10, Color.BLUE); Square bObject = new Square(10, Color.BLUE); diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java similarity index 97% rename from core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index ff92410bc4..3ab8e1de91 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -7,6 +7,7 @@ import java.util.Scanner; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; +import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,7 +15,8 @@ import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; -public class JavaIoIntegrationTest { +@Ignore("need large file for testing") +public class JavaIoUnitTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); // tests - iterate lines in a file diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java rename to core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index fcc74dbe64..3b126464ab 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -public class JavaTimerUnitTest { +public class JavaTimerLongRunningUnitTest { // tests @@ -90,7 +90,6 @@ public class JavaTimerUnitTest { @Override public void run() { System.out.println("Task performed on " + new Date()); - // TODO: stop the thread } }; final Timer timer = new Timer("Timer"); diff --git a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java index ad1f2dc70c..885c3bcd6c 100644 --- a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java @@ -7,11 +7,11 @@ import org.junit.Test; public class ArraysJoinAndSplitJUnitTest { - private final String[] sauces = {"Marinara", "Olive Oil"}; - private final String[] cheeses = {"Mozzarella", "Feta", "Parmesan"}; - private final String[] vegetables = {"Olives", "Spinach", "Green Peppers"}; + private final String[] sauces = { "Marinara", "Olive Oil" }; + private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" }; + private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" }; - private final String[] customers = {"Jay", "Harry", "Ronnie", "Gary", "Ross"}; + private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" }; @Test public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() { @@ -25,12 +25,9 @@ public class ArraysJoinAndSplitJUnitTest { System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length); - Assert.assertArrayEquals(toppings, - new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta", - "Parmesan", "Olives", "Spinach", "Green Peppers"}); + Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" }); } - @Test public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() { int ordersHalved = (customers.length / 2) + (customers.length % 2); @@ -38,7 +35,7 @@ public class ArraysJoinAndSplitJUnitTest { String[] driverOne = Arrays.copyOf(customers, ordersHalved); String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length); - Assert.assertArrayEquals(driverOne, new String[]{"Jay", "Harry", "Ronnie"}); - Assert.assertArrayEquals(driverTwo, new String[]{"Gary", "Ross"}); + Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" }); + Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" }); } } diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java similarity index 85% rename from core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java rename to core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java index 30b0111555..5d07628a96 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java @@ -12,16 +12,13 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.*; -public class ArrayListTest { +public class ArrayListUnitTest { private List stringsToSearch; @Before public void setUp() { - List list = LongStream.range(0, 16) - .boxed() - .map(Long::toHexString) - .collect(toCollection(ArrayList::new)); + List list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new)); stringsToSearch = new ArrayList<>(list); stringsToSearch.addAll(list); } @@ -34,8 +31,7 @@ public class ArrayListTest { @Test public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { - Collection numbers = - IntStream.range(0, 10).boxed().collect(toSet()); + Collection numbers = IntStream.range(0, 10).boxed().collect(toSet()); List list = new ArrayList<>(numbers); assertEquals(10, list.size()); @@ -56,8 +52,7 @@ public class ArrayListTest { @Test public void givenCollection_whenAddToArrayList_thenIsAdded() { List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); - LongStream.range(4, 10).boxed() - .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); + LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list)); } @@ -88,10 +83,7 @@ public class ArrayListTest { public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() { Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); - List result = stringsToSearch - .stream() - .filter(matchingStrings::contains) - .collect(toCollection(ArrayList::new)); + List result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new)); assertEquals(6, result.size()); } @@ -131,8 +123,7 @@ public class ArrayListTest { @Test public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() { - Set matchingStrings - = Sets.newHashSet("a", "b", "c", "d", "e", "f"); + Set matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f"); Iterator it = stringsToSearch.iterator(); while (it.hasNext()) { diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java similarity index 60% rename from core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java rename to core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java index a6814ee600..bb3abff28d 100644 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java @@ -1,21 +1,21 @@ package org.baeldung.java.enums; - -import com.baeldung.enums.Pizza; -import org.junit.Test; +import static junit.framework.TestCase.assertTrue; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; -import static junit.framework.TestCase.assertTrue; +import org.junit.Test; +import com.baeldung.enums.Pizza; + +public class PizzaUnitTest { -public class PizzaTest { @Test public void givenPizaOrder_whenReady_thenDeliverable() { Pizza testPz = new Pizza(); - testPz.setStatus(Pizza.PizzaStatus.READY); + testPz.setStatus(Pizza.PizzaStatusEnum.READY); assertTrue(testPz.isDeliverable()); } @@ -23,16 +23,16 @@ public class PizzaTest { public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); @@ -48,33 +48,34 @@ public class PizzaTest { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); pzList.add(pz3); pzList.add(pz4); - EnumMap> map = Pizza.groupPizzaByStatus(pzList); - assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1); - assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2); - assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1); + EnumMap> map = Pizza.groupPizzaByStatus(pzList); + assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); + assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); + assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); } @Test public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { Pizza pz = new Pizza(); - pz.setStatus(Pizza.PizzaStatus.READY); + pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.deliver(); - assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED); + assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); } + } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java similarity index 86% rename from core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java index 24213ba869..4b56a97325 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java @@ -13,7 +13,7 @@ import java.nio.file.Paths; import org.apache.commons.io.FileUtils; import org.junit.Test; -public class JavaFileIntegrationTest { +public class JavaFileUnitTest { // create a file @@ -46,7 +46,7 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException { final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt"); - fileToMove.exists(); + fileToMove.createNewFile();// .exists(); final File destDir = new File("src/test/resources/"); destDir.mkdir(); @@ -68,7 +68,7 @@ public class JavaFileIntegrationTest { public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException { final File fileToMove = new File("src/test/resources/fileToMove.txt"); fileToMove.createNewFile(); - final File destDir = new File("src/test/resources/"); + final File destDir = new File("src/main/resources/"); final File targetFile = new File(destDir, fileToMove.getName()); com.google.common.io.Files.createParentDirs(targetFile); com.google.common.io.Files.move(fileToMove, targetFile); @@ -76,13 +76,14 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException { - FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/test/resources/fileMoved.txt")); + FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); + FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt")); } @Test public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove.txt")); - FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true); + FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); + FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true); } // delete a file @@ -99,7 +100,7 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { - // Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); Files.delete(fileToDeletePath); @@ -117,7 +118,7 @@ public class JavaFileIntegrationTest { @Test public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { - // FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java similarity index 97% rename from core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index e679b82d3f..b1aa58424d 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -23,7 +23,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaReadFromFileTest { +public class JavaReadFromFileUnitTest { @Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { @@ -115,7 +115,7 @@ public class JavaReadFromFileTest { final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); - + System.out.println(currentLine); assertEquals(expected_value, currentLine); } @@ -143,8 +143,9 @@ public class JavaReadFromFileTest { final FileChannel channel = reader.getChannel(); int bufferSize = 1024; - if (bufferSize > channel.size()) + if (bufferSize > channel.size()) { bufferSize = (int) channel.size(); + } final ByteBuffer buff = ByteBuffer.allocate(bufferSize); channel.read(buff); buff.flip(); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 61f0f52316..5af286dbca 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -15,7 +15,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaScannerTest { +public class JavaScannerUnitTest { @Test public void whenReadFileWithScanner_thenCorrect() throws IOException { diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java index 93cfffa39d..9ff95c4e16 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java @@ -26,7 +26,7 @@ import java.nio.file.Paths; import org.junit.Test; -public class JavaWriteToFileTest { +public class JavaWriteToFileUnitTest { private String fileName = "src/test/resources/test_write.txt"; private String fileName1 = "src/test/resources/test_write_1.txt"; diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java similarity index 83% rename from core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java index b8926946a9..c609f5badb 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ListAssertJTest { +public class ListAssertJUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); @@ -15,9 +15,7 @@ public class ListAssertJTest { @Test public void whenTestingForEquality_ShouldBeEqual() throws Exception { - assertThat(list1) - .isEqualTo(list2) - .isNotEqualTo(list3); + assertThat(list1).isEqualTo(list2).isNotEqualTo(list3); assertThat(list1.equals(list2)).isTrue(); assertThat(list1.equals(list3)).isFalse(); diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java index fa80d0e224..b7c2bd7272 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java @@ -6,7 +6,7 @@ import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; -public class ListTestNGTest { +public class ListTestNgUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java similarity index 77% rename from core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java rename to core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java index 83f1fb33b6..55e71470c8 100644 --- a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java @@ -1,9 +1,10 @@ package org.baeldung.java.md5; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; +import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -11,80 +12,64 @@ import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; import org.apache.commons.codec.digest.DigestUtils; -import org.junit.Before; import org.junit.Test; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; -import java.io.File; -import java.io.IOException; -import java.nio.*; -import static org.assertj.core.api.Assertions.assertThat; +public class JavaMD5UnitTest { - -public class JavaMD5Test { - - String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - - - + @Test public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); - + assertThat(myHash.equals(hash)).isTrue(); } - + @Test public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Files.readAllBytes(Paths.get(filename))); byte[] digest = md.digest(); - String myChecksum = DatatypeConverter - .printHexBinary(digest).toUpperCase(); - + String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - + @Test - public void givenPassword_whenHashingUsingCommons_thenVerifying() { + public void givenPassword_whenHashingUsingCommons_thenVerifying() { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - String md5Hex = DigestUtils - .md5Hex(password).toUpperCase(); - + String md5Hex = DigestUtils.md5Hex(password).toUpperCase(); + assertThat(md5Hex.equals(hash)).isTrue(); } - - + @Test public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - HashCode hash = com.google.common.io.Files - .hash(new File(filename), Hashing.md5()); - String myChecksum = hash.toString() - .toUpperCase(); - + + HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString().toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - } diff --git a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java rename to core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java index 5127ccb10c..bb849d6a13 100644 --- a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java +++ b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java @@ -6,7 +6,7 @@ import java.util.TimerTask; import org.junit.Test; -public class SandboxJavaTest { +public class SandboxJavaManualTest { @Test public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { diff --git a/core-java/src/test/resources/testFolder/sample_file_1.in b/core-java/src/test/resources/testFolder/sample_file_1.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/core-java/src/test/resources/testFolder/sample_file_1.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/core-java/src/test/resources/testFolder/sample_file_2.in b/core-java/src/test/resources/testFolder/sample_file_2.in new file mode 100644 index 0000000000..93b493a513 --- /dev/null +++ b/core-java/src/test/resources/testFolder/sample_file_2.in @@ -0,0 +1 @@ +Hello world ! \ No newline at end of file diff --git a/couchbase-sdk/pom.xml b/couchbase-sdk/pom.xml index 4c277f4c85..b7b3d1788f 100644 --- a/couchbase-sdk/pom.xml +++ b/couchbase-sdk/pom.xml @@ -85,6 +85,17 @@ 1.7 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + @@ -97,6 +108,7 @@ 1.7.12 4.11 3.4 + 2.19.1 diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java similarity index 98% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java index afc5bbd53b..5907a4cc63 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java @@ -21,7 +21,7 @@ import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceTest extends AsyncIntegrationTest { +public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java similarity index 94% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java index 8ecb51a4b9..08e3728c77 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java @@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends AsyncIntegrationTest { +public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java similarity index 97% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java index 601b261f6e..b3fadae6ca 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.baeldung.couchbase.spring.IntegrationTest; -public class PersonCrudServiceTest extends IntegrationTest { +public class PersonCrudServiceIntegrationTest extends IntegrationTest { private static final String CLARK_KENT = "Clark Kent"; private static final String SMALLVILLE = "Smallville"; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java similarity index 94% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java index d1968e1c04..f3ee4585a3 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java @@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends IntegrationTest { +public class ClusterServiceIntegrationTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/feign-client/README.md b/feign/README.md similarity index 100% rename from feign-client/README.md rename to feign/README.md 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/.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-migration/README.MD b/flyway/README.MD similarity index 100% rename from flyway-migration/README.MD rename to flyway/README.MD 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/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index e662219718..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,6 +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. - -###Relevant Articles: -- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance) diff --git a/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java index 5bbf776705..92468683bf 100644 --- a/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java +++ b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java @@ -1,7 +1,10 @@ package org.baeldung.gson.entities; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.TimeZone; public class ActorGson { @@ -18,7 +21,7 @@ public class ActorGson { @Override public String toString() { - return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; } public String getImdbId() { @@ -45,5 +48,10 @@ public class ActorGson { this.filmography = filmography; } + private String formatDateOfBirth() { + final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); + formatter.setTimeZone(TimeZone.getTimeZone("GMT")); + return formatter.format(dateOfBirth); + } } \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java index 70a03500d5..016e3ba1e2 100644 --- a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java +++ b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java @@ -1,27 +1,33 @@ package org.baeldung.gson.serialization; -import com.google.gson.*; -import org.baeldung.gson.entities.ActorGson; - import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; +import org.baeldung.gson.entities.ActorGson; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + public class ActorGsonDeserializer implements JsonDeserializer { - private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); @Override public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { - JsonObject jsonObject = json.getAsJsonObject(); + final JsonObject jsonObject = json.getAsJsonObject(); - JsonElement jsonImdbId = jsonObject.get("imdbId"); - JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); - JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); + final JsonElement jsonImdbId = jsonObject.get("imdbId"); + final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); + final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); - ArrayList filmList = new ArrayList(); + final ArrayList filmList = new ArrayList(); if (jsonFilmography != null) { for (int i = 0; i < jsonFilmography.size(); i++) { filmList.add(jsonFilmography.get(i).getAsString()); @@ -31,7 +37,7 @@ public class ActorGsonDeserializer implements JsonDeserializer { ActorGson actorGson = null; try { actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList); - } catch (ParseException e) { + } catch (final ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java index d87f0f4bd9..3844c55cd8 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java @@ -1,38 +1,40 @@ package org.baeldung.gson.deserialization; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.text.ParseException; + import org.baeldung.gson.entities.ActorGson; import org.baeldung.gson.entities.Movie; import org.baeldung.gson.serialization.ActorGsonDeserializer; import org.junit.Assert; import org.junit.Test; -import java.text.ParseException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; public class GsonDeserializeTest { - @Test public void whenSimpleDeserialize_thenCorrect() throws ParseException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Tue Sep 21 11:00:00 GMT 1982\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Movie outputMovie = new Gson().fromJson(jsonInput, Movie.class); + final Gson gson = new GsonBuilder().setDateFormat("EEE MMM dd hh:mm:ss zzz yyyy").create(); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final Movie outputMovie = gson.fromJson(jsonInput, Movie.class); + + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(outputMovie.toString(), expectedOutput); } @Test public void whenCustomDeserialize_thenCorrect() throws ParseException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create(); + final Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create(); - Movie outputMovie = gson.fromJson(jsonInput, Movie.class); + final Movie outputMovie = gson.fromJson(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(outputMovie.toString(), expectedOutput); } } diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 66b2076852..cac363c414 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -141,12 +141,52 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + + + + 4.3.11.Final diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index bfe1e68ebe..b1399dcab8 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -51,7 +51,7 @@ public class HttpAsyncClientLiveTest { @Test public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); - // client.start(); + client.start(); final HttpGet request = new HttpGet(HOST); final Future future = client.execute(request, null); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java similarity index 98% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 371657af62..6fad126537 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -28,15 +28,17 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; -public class HttpClientMultipartTest { +@Ignore("Server is not available") +public class HttpClientMultipartLiveTest { private static final String SERVER = "http://echo.200please.com"; private static final String TEXTFILENAME = "temp.txt"; private static final String IMAGEFILENAME = "image.jpg"; private static final String ZIPFILENAME = "zipFile.zip"; - private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartTest"); + private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartLiveTest"); private CloseableHttpClient client; private HttpPost post; private BufferedReader rd; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java similarity index 98% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index 7b75cdfc19..ada5667f0b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -29,7 +29,10 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; -public class HttpClientPostingTest { +/* + * NOTE : Need module spring-rest to be running + */ +public class HttpClientPostingLiveTest { private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 952ce3af25..fb272b0a33 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,21 +1,23 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.io.IOException; import java.security.GeneralSecurityException; -import java.security.cert.X509Certificate; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; 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.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.SSLContexts; @@ -42,7 +44,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 +55,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 +72,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 +100,25 @@ public class HttpsClientSslLiveTest { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } + @Test + public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { + + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; + + SSLContext sslContext = null; + try { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build(); + + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + e.printStackTrace(); + } + + final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + final HttpGet httpGet = new HttpGet(HOST_WITH_SSL); + 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/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 2333e2f8c9..40216a70a5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -6,29 +6,31 @@ 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.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.junit.After; import org.junit.Test; +/* + * NOTE : Need module spring-security-rest-basic-auth to be running + */ 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; + final 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"); + final CloseableHttpResponse response = client.execute(httpGet); + + System.out.println(response.getStatusLine()); try { final HttpEntity entity = response.getEntity(); @@ -41,33 +43,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()); - } - - @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - - final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); - httpGet.setHeader("Accept", "application/xml"); - - response = httpClient.execute(httpGet); - } - } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java index 495d46e91f..e98dd4d14f 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java @@ -30,6 +30,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +/* + * NOTE : Need module spring-security-rest-basic-auth to be running + */ + public class HttpClientAuthLiveTest { private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1"; 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/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java index 68cd6117d6..375b2204ff 100644 --- a/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java +++ b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java @@ -1,7 +1,10 @@ package org.baeldung.jackson.entities; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.TimeZone; public class ActorJackson { @@ -22,7 +25,7 @@ public class ActorJackson { @Override public String toString() { - return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; } public String getImdbId() { @@ -49,4 +52,9 @@ public class ActorJackson { this.filmography = filmography; } + private String formatDateOfBirth() { + final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); + formatter.setTimeZone(TimeZone.getTimeZone("GMT")); + return formatter.format(dateOfBirth); + } } diff --git a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java index 71d5ad3d81..503b6eb99b 100644 --- a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java @@ -1,39 +1,40 @@ package org.baeldung.jackson.deserialization; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.baeldung.jackson.entities.Movie; -import org.junit.Assert; -import org.junit.Test; - import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; +import org.baeldung.jackson.entities.Movie; +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; + public class JacksonDeserializeTest { @Test public void whenSimpleDeserialize_thenCorrect() throws IOException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - ObjectMapper mapper = new ObjectMapper(); - Movie movie = mapper.readValue(jsonInput, Movie.class); + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final ObjectMapper mapper = new ObjectMapper(); + final Movie movie = mapper.readValue(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(movie.toString(), expectedOutput); } @Test public void whenCustomDeserialize_thenCorrect() throws IOException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - ObjectMapper mapper = new ObjectMapper(); - final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + final ObjectMapper mapper = new ObjectMapper(); + final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); mapper.setDateFormat(df); - Movie movie = mapper.readValue(jsonInput, Movie.class); + final Movie movie = mapper.readValue(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(movie.toString(), expectedOutput); } diff --git a/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java index 6c8aa90fae..6d9e378025 100644 --- a/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java @@ -1,22 +1,19 @@ package org.baeldung.jackson.serialization; import java.io.IOException; -import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.TimeZone; import org.baeldung.jackson.entities.ActorJackson; import org.baeldung.jackson.entities.Movie; import org.baeldung.jackson.entities.MovieWithNullValue; -import org.baeldung.jackson.serialization.ActorJacksonSerializer; import org.junit.Assert; import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -26,34 +23,35 @@ public class JacksonSerializeTest { @Test public void whenSimpleSerialize_thenCorrect() throws JsonProcessingException, ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); + final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + final Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); - ObjectMapper mapper = new ObjectMapper(); - String jsonResult = mapper.writeValueAsString(movie); + final ObjectMapper mapper = new ObjectMapper(); + final String jsonResult = mapper.writeValueAsString(movie); - String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401439600000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401414400000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; Assert.assertEquals(jsonResult, expectedOutput); } @Test public void whenCustomSerialize_thenCorrect() throws ParseException, IOException { - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); + final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); - SimpleModule module = new SimpleModule(); + final SimpleModule module = new SimpleModule(); module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); - ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); - String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); - Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); + final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); Assert.assertEquals(jsonResult, expectedOutput); } diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml index a91c3b9b62..92d3a8ede6 100644 --- a/java-cassandra/pom.xml +++ b/java-cassandra/pom.xml @@ -76,8 +76,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 + + + + + + + UTF-8 @@ -97,6 +143,7 @@ 3.5.1 + 2.19.1 3.1.0 diff --git a/jee7schedule/README.md b/jee7/README.md similarity index 100% rename from jee7schedule/README.md rename to jee7/README.md 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/jooq-spring/README.md b/jooq-spring/README.md deleted file mode 100644 index 79718e74c6..0000000000 --- a/jooq-spring/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### 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/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml index b2ebaa32e2..b5a2e8693c 100644 --- a/jpa-storedprocedure/pom.xml +++ b/jpa-storedprocedure/pom.xml @@ -11,6 +11,7 @@ 7.0 5.1.0.Final 5.1.38 + 2.19.1 @@ -33,6 +34,16 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index 69351d9683..c93d59fe30 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureTest { +public class StoredProcedureIntegrationTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/junit5/src/test/java/com/baeldung/FirstTest.java b/junit5/src/test/java/com/baeldung/FirstTest.java index 4fc6037174..3306dc01f9 100644 --- a/junit5/src/test/java/com/baeldung/FirstTest.java +++ b/junit5/src/test/java/com/baeldung/FirstTest.java @@ -19,6 +19,7 @@ class FirstTest { .sum() > 5, "Sum should be greater than 5"); } + @Disabled("test to show MultipleFailuresError") @Test void groupAssertions() { int[] numbers = {0, 1, 2, 3, 4}; 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/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml new file mode 100644 index 0000000000..2dabf484e1 --- /dev/null +++ b/patterns/front-controller/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + front-controller + war + + + patterns-parent + com.baeldung.patterns + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + + + org.eclipse.jetty + jetty-maven-plugin + + + /front-controller + + + + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java similarity index 76% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java index a8962f5108..9fb120399c 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java @@ -1,7 +1,7 @@ -package com.baeldung.enterprise.patterns.front.controller; +package com.baeldung.patterns.front.controller; -import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; -import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; +import com.baeldung.patterns.front.controller.commands.FrontCommand; +import com.baeldung.patterns.front.controller.commands.UnknownCommand; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -24,7 +24,7 @@ public class FrontControllerServlet extends HttpServlet { try { Class type = Class.forName( String.format( - "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + "com.baeldung.patterns.front.controller.commands.%sCommand", request.getParameter("command") ) ); diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java similarity index 93% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java index 12a008faeb..cc92731050 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java similarity index 69% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java index 0c5bd64bbc..21028b07f0 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java @@ -1,7 +1,7 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; -import com.baeldung.enterprise.patterns.front.controller.data.Book; -import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; +import com.baeldung.patterns.front.controller.data.Book; +import com.baeldung.patterns.front.controller.data.BookshelfImpl; import javax.servlet.ServletException; import java.io.IOException; diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java similarity index 77% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java index 90103c8f42..9f24746598 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; import javax.servlet.ServletException; import java.io.IOException; diff --git a/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..5a15df92c4 --- /dev/null +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.front.controller.data; + +public interface Book { + String getAuthor(); + + void setAuthor(String author); + + String getTitle(); + + void setTitle(String title); + + Double getPrice(); + + void setPrice(Double price); +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java similarity index 69% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java index 634e05c3a0..0421ff5623 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java @@ -1,39 +1,45 @@ -package com.baeldung.enterprise.patterns.front.controller.data; +package com.baeldung.patterns.front.controller.data; -public class Book { +public class BookImpl implements Book { private String author; private String title; private Double price; - public Book() { + public BookImpl() { } - public Book(String author, String title, Double price) { + public BookImpl(String author, String title, Double price) { this.author = author; this.title = title; this.price = price; } + @Override public String getAuthor() { return author; } + @Override public void setAuthor(String author) { this.author = author; } + @Override public String getTitle() { return title; } + @Override public void setTitle(String title) { this.title = title; } + @Override public Double getPrice() { return price; } + @Override public void setPrice(Double price) { this.price = price; } diff --git a/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..21e3067133 --- /dev/null +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.front.controller.data; + +public interface Bookshelf { + + default void init() { + add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + Bookshelf getInstance(); + + boolean add(E book); + + Book findByTitle(String title); +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java similarity index 89% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java index 3862418857..dd1fa4e523 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.data; +package com.baeldung.patterns.front.controller.data; import java.util.ArrayList; diff --git a/patterns/front-controller/src/main/resources/front controller.png b/patterns/front-controller/src/main/resources/front controller.png new file mode 100644 index 0000000000..bd475bf3f3 Binary files /dev/null and b/patterns/front-controller/src/main/resources/front controller.png differ diff --git a/patterns/front-controller/src/main/resources/front controller.puml b/patterns/front-controller/src/main/resources/front controller.puml new file mode 100644 index 0000000000..fbd4f416ef --- /dev/null +++ b/patterns/front-controller/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml + +class Handler { +doGet +doPost +} + +abstract class AbstractCommand { +process +} +class ConcreteCommand1 { +process +} +class ConcreteCommand2 { +process +} + +Handler .right.> AbstractCommand +AbstractCommand <|-- ConcreteCommand1 +AbstractCommand <|-- ConcreteCommand2 + +@enduml \ No newline at end of file diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-found.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-found.jsp diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-notfound.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-notfound.jsp diff --git a/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/unknown.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/unknown.jsp diff --git a/patterns/src/main/webapp/WEB-INF/web.xml b/patterns/front-controller/src/main/webapp/WEB-INF/web.xml similarity index 82% rename from patterns/src/main/webapp/WEB-INF/web.xml rename to patterns/front-controller/src/main/webapp/WEB-INF/web.xml index 77113db09b..4abca2bb97 100644 --- a/patterns/src/main/webapp/WEB-INF/web.xml +++ b/patterns/front-controller/src/main/webapp/WEB-INF/web.xml @@ -6,7 +6,7 @@ version="3.1"> front-controller - com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + com.baeldung.patterns.front.controller.FrontControllerServlet front-controller diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml new file mode 100644 index 0000000000..2cf89246f9 --- /dev/null +++ b/patterns/intercepting-filter/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + intercepting-filter + war + + + com.baeldung.patterns + patterns-parent + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + + + org.slf4j + slf4j-api + 1.7.21 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + org.eclipse.jetty + jetty-maven-plugin + + + / + + + + + + diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java new file mode 100644 index 0000000000..9d8a004265 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java @@ -0,0 +1,66 @@ +package com.baeldung.patterns.intercepting.filter; + +import com.baeldung.patterns.intercepting.filter.commands.FrontCommand; +import com.baeldung.patterns.intercepting.filter.commands.UnknownCommand; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; +import com.baeldung.patterns.intercepting.filter.data.BookshelfImpl; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "intercepting-filter", urlPatterns = "/") +public class FrontControllerServlet extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + Bookshelf bookshelf = new BookshelfImpl(); + bookshelf.init(); + getServletContext().setAttribute("bookshelf", bookshelf); + } + + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + doCommand(request, response); + } + + @Override + protected void doPost( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + doCommand(request, response); + } + + private void doCommand( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(request, response); + command.process(); + } + + private FrontCommand getCommand(HttpServletRequest request) { + try { + Class type = Class.forName( + String.format( + "com.baeldung.patterns.intercepting.filter.commands.%sCommand", + request.getParameter("command") + ) + ); + return (FrontCommand) type + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + return new UnknownCommand(); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java new file mode 100644 index 0000000000..fda88c741e --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java @@ -0,0 +1,27 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Order; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class CheckoutCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + HttpSession session = request.getSession(false); + if (request.getMethod().equals("POST")) { + session.removeAttribute("order"); + response.sendRedirect("/?command=Home&message=Thank you for buying!"); + } else { + Order order = (Order) session.getAttribute("order"); + Double total = order.getItems().entrySet().stream() + .map(entry -> entry.getKey().getPrice() * entry.getValue()) + .reduce((p1, p2) -> p1 + p2) + .orElse(0.00); + request.setAttribute("total", total); + forward("shopping-cart"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java new file mode 100644 index 0000000000..a3c545703b --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java @@ -0,0 +1,43 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.filters.FilterManager; +import com.baeldung.patterns.intercepting.filter.filters.OnIntercept; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand implements OnIntercept { + protected HttpServletRequest request; + protected HttpServletResponse response; + private boolean intercept; + + public FrontCommand() { + } + + public void init(HttpServletRequest request, HttpServletResponse response) { + this.request = request; + this.response = response; + } + + public void process() throws ServletException, IOException { + FilterManager.process(request, response, this); + } + + public void forward(String target) throws ServletException, IOException { + if (intercept) { + return; + } + String path = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = request.getServletContext() + .getRequestDispatcher(path); + dispatcher.forward(request, response); + } + + @Override + public void intercept() { + intercept = true; + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java new file mode 100644 index 0000000000..33e60b44b5 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java @@ -0,0 +1,17 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class HomeCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + request.setAttribute("books", bookshelf); + forward("home"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java new file mode 100644 index 0000000000..46a0329112 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java @@ -0,0 +1,23 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.Optional; + +public class LoginCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + if (request.getMethod().equals("POST")) { + HttpSession session = request.getSession(true); + session.setAttribute("username", request.getParameter("username")); + response.sendRedirect(request.getParameter("redirect")); + } else { + String queryString = Optional.ofNullable(request.getQueryString()) + .orElse("command=Home"); + request.setAttribute("redirect", request.getRequestURL() + .append("?").append(queryString).toString()); + forward("login"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java new file mode 100644 index 0000000000..f309dc5cf3 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java @@ -0,0 +1,19 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.Optional; + +public class LogoutCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Optional.ofNullable(request.getSession(false)) + .ifPresent(session -> { + session.removeAttribute("username"); + session.removeAttribute("order"); + }); + response.sendRedirect("/?command=Home"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java new file mode 100644 index 0000000000..a57785669b --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java @@ -0,0 +1,33 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; +import com.baeldung.patterns.intercepting.filter.data.Order; +import com.baeldung.patterns.intercepting.filter.data.OrderImpl; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.Optional; + +public class OrderCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + if (request.getMethod().equals("POST")) { + HttpSession session = request.getSession(false); + Order order = Optional + .ofNullable(session.getAttribute("order")) + .map(Order.class::cast) + .orElseGet(() -> new OrderImpl((String) session.getAttribute("username"))); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String isbn = request.getParameter("isbn"); + Integer quantity = Integer.parseInt(request.getParameter("quantity")); + Book book = bookshelf.get(isbn); + order.add(book, quantity); + session.setAttribute("order", order); + response.sendRedirect(String.format("/?command=Show&isbn=%s", isbn)); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java new file mode 100644 index 0000000000..6c52f4f5a9 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.List; + +public class SearchCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String q = request.getParameter("q"); + List books = bookshelf.find(q); + if (books.size() > 0) { + request.setAttribute("books", books); + forward("book-found"); + } else { + forward("book-notfound"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java new file mode 100644 index 0000000000..1ea5ca6edb --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java @@ -0,0 +1,21 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.Collections; + +public class ShowCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String title = request.getParameter("isbn"); + Book book = bookshelf.get(title); + request.setAttribute("books", Collections.singletonList(book)); + forward("book-found"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java new file mode 100644 index 0000000000..427efe5aba --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java @@ -0,0 +1,12 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + forward("unknown"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java new file mode 100644 index 0000000000..4e98095c2c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java @@ -0,0 +1,19 @@ +package com.baeldung.patterns.intercepting.filter.data; + +public interface Book { + String getIsbn(); + + void setIsbn(String isbn); + + String getAuthor(); + + void setAuthor(String author); + + String getTitle(); + + void setTitle(String title); + + Double getPrice(); + + void setPrice(Double price); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java new file mode 100644 index 0000000000..cd0c0924e2 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java @@ -0,0 +1,58 @@ +package com.baeldung.patterns.intercepting.filter.data; + +public class BookImpl implements Book { + private String isbn; + private String author; + private String title; + private Double price; + + public BookImpl() { + } + + public BookImpl(String isbn, String author, String title, Double price) { + this.isbn = isbn; + this.author = author; + this.title = title; + this.price = price; + } + + @Override + public String getIsbn() { + return isbn; + } + + @Override + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + @Override + public String getAuthor() { + return author; + } + + @Override + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String getTitle() { + return title; + } + + @Override + public void setTitle(String title) { + this.title = title; + } + + @Override + public Double getPrice() { + return price; + } + + @Override + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java new file mode 100644 index 0000000000..26541de8e0 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java @@ -0,0 +1,18 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.List; + +public interface Bookshelf { + + default void init() { + add(new BookImpl("001", "Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new BookImpl("002", "Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + add(new BookImpl("003", "Unknown", "Something about German Umlauts (äüö) and ß", 5.49)); + } + + boolean add(E book); + + Book get(String isbn); + + List find(String q); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java new file mode 100644 index 0000000000..5767af8e50 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java @@ -0,0 +1,23 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + @Override + public Book get(String isbn) { + return this.stream() + .filter(book -> book.getIsbn().equals(isbn)) + .findFirst() + .orElse(null); + } + + @Override + public List find(String q) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(q.toLowerCase()) + || book.getAuthor().toLowerCase().contains(q.toLowerCase())) + .collect(Collectors.toList()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java new file mode 100644 index 0000000000..f4a32002d7 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java @@ -0,0 +1,11 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.Map; + +public interface Order { + String getUsername(); + + Map getItems(); + + void add(Book item, Integer quantity); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java new file mode 100644 index 0000000000..9f50e45082 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java @@ -0,0 +1,40 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.HashMap; +import java.util.Map; + +public class OrderImpl implements Order { + private String username; + private Map items = new HashMap<>(); + + public OrderImpl(String username) { + this.username = username; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public Map getItems() { + return items; + } + + public void setItems(Map items) { + this.items = items; + } + + @Override + public void add(Book item, Integer quantity) { + Integer q = 0; + if (this.items.containsKey(item)) { + q = this.items.get(item); + } + this.items.put(item, quantity + q); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java new file mode 100644 index 0000000000..a2cac9d84c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java @@ -0,0 +1,45 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import com.baeldung.patterns.intercepting.filter.commands.FrontCommand; +import com.baeldung.patterns.intercepting.filter.commands.LoginCommand; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class AuthenticationFilter implements Filter { + private OnIntercept callback; + + public AuthenticationFilter(OnIntercept callback) { + this.callback = callback; + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + HttpSession session = httpServletRequest.getSession(false); + if (session == null || session.getAttribute("username") == null) { + callback.intercept(); + FrontCommand command = new LoginCommand(); + command.init(httpServletRequest, httpServletResponse); + command.process(); + } else { + chain.doFilter(request, response); + } + } + + @Override + public void destroy() { + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java new file mode 100644 index 0000000000..90d13a6eda --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.Filter; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; + +public abstract class BaseFilter implements Filter { + private static final Logger log = LoggerFactory.getLogger(BaseFilter.class); + + protected FilterConfig filterConfig; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + log.info("Initialize filter: {}", getClass().getSimpleName()); + this.filterConfig = filterConfig; + } + + @Override + public void destroy() { + log.info("Destroy filter: {}", getClass().getSimpleName()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java new file mode 100644 index 0000000000..0806aecba3 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; +import java.io.IOException; +import java.util.Optional; + +@WebFilter( + servletNames = {"intercepting-filter"}, + initParams = {@WebInitParam(name = "encoding", value = "UTF-8")} +) +public class EncodingFilter extends BaseFilter { + private String encoding; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + super.init(filterConfig); + this.encoding = filterConfig.getInitParameter("encoding"); + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + String encoding = Optional + .ofNullable(request.getParameter("encoding")) + .orElse(this.encoding); + response.setCharacterEncoding(encoding); + chain.doFilter(request, response); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java new file mode 100644 index 0000000000..80ddef785c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; + +public class FilterChainImpl implements FilterChain { + private Iterator filters; + + public FilterChainImpl(Filter... filters) { + this.filters = Arrays.asList(filters).iterator(); + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response + ) throws IOException, ServletException { + if (filters.hasNext()) { + Filter filter = filters.next(); + filter.doFilter(request, response, this); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java new file mode 100644 index 0000000000..2f7b7ac703 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java @@ -0,0 +1,21 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FilterManager { + public static void process( + HttpServletRequest request, + HttpServletResponse response, + OnIntercept callback + ) throws ServletException, IOException { + FilterChain filterChain = new FilterChainImpl( + new AuthenticationFilter(callback), + new VisitorCounterFilter() + ); + filterChain.doFilter(request, response); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java new file mode 100644 index 0000000000..322592f84e --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Optional; + +@WebFilter(servletNames = "intercepting-filter") +public class LoggingFilter extends BaseFilter { + private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class); + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + chain.doFilter(request, response); + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String username = Optional + .ofNullable(httpServletRequest.getAttribute("username")) + .map(Object::toString) + .orElse("guest"); + log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(), + httpServletRequest.getRequestURI(), request.getParameterMap()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java new file mode 100644 index 0000000000..1a138f1e1c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java @@ -0,0 +1,5 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +public interface OnIntercept { + void intercept(); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java new file mode 100644 index 0000000000..64396ef931 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class TemplateFilter extends BaseFilter { + protected abstract void preFilter( + HttpServletRequest request, + HttpServletResponse response + ) throws IOException, ServletException; + + protected abstract void postFilter( + HttpServletRequest request, + HttpServletResponse response + ) throws IOException, ServletException; + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + preFilter(httpServletRequest, httpServletResponse); + chain.doFilter(request, response); + postFilter(httpServletRequest, httpServletResponse); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java new file mode 100644 index 0000000000..42551310d3 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java @@ -0,0 +1,35 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +public class VisitorCounterFilter implements Filter { + private static Set users = new HashSet<>(); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpSession session = ((HttpServletRequest) request).getSession(false); + Optional.ofNullable(session.getAttribute("username")) + .map(Object::toString) + .ifPresent(users::add); + request.setAttribute("counter", users.size()); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } +} diff --git a/patterns/src/main/resources/front controller.png b/patterns/intercepting-filter/src/main/resources/front_controller.png similarity index 100% rename from patterns/src/main/resources/front controller.png rename to patterns/intercepting-filter/src/main/resources/front_controller.png diff --git a/patterns/src/main/resources/front controller.puml b/patterns/intercepting-filter/src/main/resources/front_controller.puml similarity index 100% rename from patterns/src/main/resources/front controller.puml rename to patterns/intercepting-filter/src/main/resources/front_controller.puml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png new file mode 100644 index 0000000000..2f025fad5e Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml new file mode 100644 index 0000000000..4090085d85 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml @@ -0,0 +1,29 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +class FilterManager { + {static} void process() +} +class FilterChainImpl { + void doFilter() +} +class AuthenticationFilter { + void doFilter() +} +class VisitorCounterFilter { + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet -- FrontCommand +FrontCommand .right.-- FilterManager +FilterManager -- FilterChainImpl +FilterChainImpl .right.-- AuthenticationFilter +AuthenticationFilter .right.-- VisitorCounterFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png new file mode 100644 index 0000000000..0d8db711a7 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml new file mode 100644 index 0000000000..1261d9ee4b --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml @@ -0,0 +1,26 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +abstract class BaseFilter { + void init() + void destroy() +} +class LoggingFilter { + void doFilter() +} +class EncodingFilter { + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet .right.-- FrontCommand +FrontControllerServlet -- BaseFilter +BaseFilter <|-- LoggingFilter +BaseFilter <|-- EncodingFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png new file mode 100644 index 0000000000..5c37aa2937 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml new file mode 100644 index 0000000000..77b001f547 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml @@ -0,0 +1,25 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +abstract class BaseFilter { + void init() + void destroy() +} +abstract class TemplateFilter { + {abstract} void preFilter() + {abstract} void postFilter() + -- + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet .right.-- FrontCommand +FrontControllerServlet -- BaseFilter +BaseFilter <|-- TemplateFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter.png new file mode 100644 index 0000000000..9ccacc8081 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml new file mode 100644 index 0000000000..b06b822323 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml @@ -0,0 +1,17 @@ +@startuml +scale 1.5 + +class Client +class FilterManager +interface FilterChain +interface "Filter 1" +interface "Filter 2" +interface "Filter 3" + +Client .right.-- FilterManager +FilterManager .right.-- Target +FilterManager -- FilterChain +FilterChain .right.-- "Filter 3" +FilterChain .right.-- "Filter 2" +FilterChain .right.-- "Filter 1" +@enduml diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..4de1d3ca23 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,24 @@ +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Book" %> +<%@ page import="java.util.List" %> + + + + Bookshelf: Title found + + +

Our Bookshelf contains following titles:

+ <% for (Book book : (List) request.getAttribute("books")) { %> +

<%= book.getTitle() %>

+

Author: <%= book.getAuthor() %>

+
+ + + + + Go back... +
+ <% } %> + <%@ include file="shopping-cart-hint.jsp"%> + <%@ include file="visitor-counter.jsp"%> + + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-notfound.jsp new file mode 100644 index 0000000000..284b1e4759 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-notfound.jsp @@ -0,0 +1,11 @@ + + + + Bookshelf: Title not found + + +

Our Bookshelf doesn't contains this title:

+

<%= request.getParameter("q") %>

+ <%@ include file="visitor-counter.jsp"%> + + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/home.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/home.jsp new file mode 100644 index 0000000000..2c2d7c2f22 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/home.jsp @@ -0,0 +1,27 @@ +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Book" %> +<%@ page import="java.util.List" %> + + + + Bookshelf: Home + + +
+ + +
+ <% if (request.getParameter("message") != null) { %> +

<%= request.getParameter("message") %>

+ <% } else { %> +

Welcome to the Bookshelf!

+ <% } %> + <% for (Book book : (List) request.getAttribute("books")) { %> +
+

<%= book.getAuthor() %>:

+

<%= book.getTitle() %>

+ More... + <% } %> + <%@ include file="shopping-cart-hint.jsp"%> + <%@ include file="visitor-counter.jsp"%> + + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/login.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/login.jsp new file mode 100644 index 0000000000..619068bcae --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/login.jsp @@ -0,0 +1,16 @@ + + + + Bookshelf: Login + + +

Please input a username:

+

Login

+
+ + "> + +
+ <%@ include file="visitor-counter.jsp" %> + + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart-hint.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart-hint.jsp new file mode 100644 index 0000000000..7e0c051540 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart-hint.jsp @@ -0,0 +1,16 @@ +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Order" %> +<% if (session != null && session.getAttribute("order") != null) { %> + <% Order order = ((Order) session.getAttribute("order")); %> + <% if (order != null && order.getItems().size() > 0) { %> +
+

+ Your shopping cart is holding + <% if (order.getItems().size() == 1) { %> + 1 item. + <% } else { %> + <%= (order.getItems().size()) %> items. + <% } %> + Checkout +

+ <% } %> +<% } %> diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp new file mode 100644 index 0000000000..5f71d2e54e --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/shopping-cart.jsp @@ -0,0 +1,29 @@ +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Book" %> +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Order" %> +<%@ page import="java.util.Map" %> + + + + Bookshelf: Checkout + + +

You are about to buy the following books:

+

Shopping Cart

+ <% Order order = (Order) session.getAttribute("order"); %> +
    + <% for (Map.Entry entry : order.getItems().entrySet()) { %> +
  • + <%= entry.getValue() %> x <%= entry.getKey().getPrice() %> +

    <%= entry.getKey().getTitle() %>

    + by <%= entry.getKey().getAuthor()%> +
  • + <% } %> +
+

+ Total: <%= request.getAttribute("total") %> +

+
+ +
+ + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/unknown.jsp new file mode 100644 index 0000000000..b52b2de8d5 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/unknown.jsp @@ -0,0 +1,9 @@ + + + + Bookshelf: Command unknown + + +

Sorry, this command is not known!

+ + diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/visitor-counter.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/visitor-counter.jsp new file mode 100644 index 0000000000..de1c741fb1 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/visitor-counter.jsp @@ -0,0 +1,5 @@ +<% Integer counter = (Integer) request.getAttribute("counter"); %> +<% if (counter != null && counter > 0) { %> +
+

You are visitor #<%= counter %>. Logout

+<% } %> diff --git a/patterns/pom.xml b/patterns/pom.xml index 7c23b6f55d..6797891353 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -4,46 +4,55 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.enterprise.patterns - patterns - war - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - + com.baeldung.patterns + patterns-parent + pom + + front-controller + intercepting-filter + com.baeldung parent-modules 1.0.0-SNAPSHOT + .. + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - org.eclipse.jetty - jetty-maven-plugin - 9.4.0.M1 - - - /front-controller - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + + org.eclipse.jetty + jetty-maven-plugin + 9.3.12.v20160915 + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java deleted file mode 100644 index 524e000bd9..0000000000 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.data; - -public interface Bookshelf { - - default void init() { - add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); - add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); - } - - Bookshelf getInstance(); - - boolean add(E book); - - Book findByTitle(String title); -} diff --git a/pdf/.gitignore b/pdf/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/pdf/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/pdf/pom.xml b/pdf/pom.xml new file mode 100644 index 0000000000..078a364e77 --- /dev/null +++ b/pdf/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + pdf + pdf + http://maven.apache.org + + + UTF-8 + 3.5.1 + + + + + junit + junit + 3.8.1 + test + + + + org.apache.pdfbox + pdfbox + 2.0.3 + + + + org.apache.pdfbox + pdfbox-tools + 2.0.3 + + + + net.sf.cssbox + pdf2dom + 1.6 + + + + com.itextpdf + itextpdf + 5.5.10 + + + + org.apache.poi + poi + 3.15 + + + + org.apache.poi + poi-ooxml + 3.15 + + + + org.apache.poi + poi-scratchpad + 3.15 + + + + org.apache.xmlgraphics + batik-transcoder + 1.8 + + + + + pdf + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java new file mode 100644 index 0000000000..14e886e23b --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java @@ -0,0 +1,39 @@ +package com.baeldung.pdf; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Writer; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.fit.pdfdom.PDFDomTree; + +public class PDF2HTMLExample { + + private static final String FILENAME = "src/main/resources/pdf.pdf"; + + public static void main(String[] args) { + try { + generateHTMLFromPDF(FILENAME); + } catch (IOException | ParserConfigurationException e) { + e.printStackTrace(); + } + } + + private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException { + try { + PDDocument pdf = PDDocument.load(new File(filename)); + PDFDomTree parser = new PDFDomTree(); + Writer output = new PrintWriter("src/output/pdf.html", "utf-8"); + parser.writeText(pdf, output); + output.close(); + if (pdf != null) { + pdf.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java new file mode 100644 index 0000000000..00778d16c1 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java @@ -0,0 +1,35 @@ +package com.baeldung.pdf; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.ImageType; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.apache.pdfbox.tools.imageio.ImageIOUtil; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +public class PDF2ImageExample { + + private static final String FILENAME = "src/main/resources/pdf.pdf"; + + public static void main(String[] args) { + try { + generateImageFromPDF(FILENAME, "png"); + generateImageFromPDF(FILENAME, "jpeg"); + generateImageFromPDF(FILENAME, "gif"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void generateImageFromPDF(String filename, String extension) throws IOException { + PDDocument document = PDDocument.load(new File(filename)); + PDFRenderer pdfRenderer = new PDFRenderer(document); + for (int page = 0; page < document.getNumberOfPages(); ++page) { + BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); + ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300); + } + document.close(); + } +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java new file mode 100644 index 0000000000..e4fb29dfaa --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java @@ -0,0 +1,52 @@ +package com.baeldung.pdf; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; + +import org.apache.pdfbox.cos.COSDocument; +import org.apache.pdfbox.io.RandomAccessFile; +import org.apache.pdfbox.pdfparser.PDFParser; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; + +public class PDF2TextExample { + + private static final String FILENAME = "src/main/resources/pdf.pdf"; + + public static void main(String[] args) { + try { + generateTxtFromPDF(FILENAME); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void generateTxtFromPDF(String filename) throws IOException { + try { + File f = new File(filename); + String parsedText; + PDFParser parser = new PDFParser(new RandomAccessFile(f, "r")); + parser.parse(); + + COSDocument cosDoc = parser.getDocument(); + + PDFTextStripper pdfStripper = new PDFTextStripper(); + PDDocument pdDoc = new PDDocument(cosDoc); + + parsedText = pdfStripper.getText(pdDoc); + + if (cosDoc != null) + cosDoc.close(); + if (pdDoc != null) + pdDoc.close(); + + PrintWriter pw = new PrintWriter("src/output/pdf.txt"); + pw.print(parsedText); + pw.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java new file mode 100644 index 0000000000..1f416592ef --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java @@ -0,0 +1,50 @@ +package com.baeldung.pdf; + +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.xwpf.usermodel.BreakType; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; + +import com.itextpdf.text.pdf.PdfReader; +import com.itextpdf.text.pdf.parser.PdfReaderContentParser; +import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; +import com.itextpdf.text.pdf.parser.TextExtractionStrategy; + +public class PDF2WordExample { + + private static final String FILENAME = "src/main/resources/pdf.pdf"; + + public static void main(String[] args) { + try { + generateDocFromPDF(FILENAME); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void generateDocFromPDF(String filename) throws IOException { + XWPFDocument doc = new XWPFDocument(); + + String pdf = filename; + PdfReader reader = new PdfReader(pdf); + PdfReaderContentParser parser = new PdfReaderContentParser(reader); + + for (int i = 1; i <= reader.getNumberOfPages(); i++) { + TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); + String text = strategy.getResultantText(); + XWPFParagraph p = doc.createParagraph(); + XWPFRun run = p.createRun(); + run.setText(text); + run.addBreak(BreakType.PAGE); + } + FileOutputStream out = new FileOutputStream("src/output/pdf.docx"); + doc.write(out); + out.close(); + reader.close(); + doc.close(); + } + +} diff --git a/pdf/src/main/resources/pdf.pdf b/pdf/src/main/resources/pdf.pdf new file mode 100644 index 0000000000..f45d226b39 Binary files /dev/null and b/pdf/src/main/resources/pdf.pdf differ diff --git a/play-framework/student-api/.gitignore b/play-framework/introduction/.gitignore similarity index 100% rename from play-framework/student-api/.gitignore rename to play-framework/introduction/.gitignore diff --git a/play-framework/student-api/LICENSE b/play-framework/introduction/LICENSE similarity index 100% rename from play-framework/student-api/LICENSE rename to play-framework/introduction/LICENSE diff --git a/play-framework/student-api/README b/play-framework/introduction/README similarity index 100% rename from play-framework/student-api/README rename to play-framework/introduction/README diff --git a/play-framework/student-api/app/Filters.java b/play-framework/introduction/app/Filters.java similarity index 100% rename from play-framework/student-api/app/Filters.java rename to play-framework/introduction/app/Filters.java diff --git a/play-framework/student-api/app/Module.java b/play-framework/introduction/app/Module.java similarity index 100% rename from play-framework/student-api/app/Module.java rename to play-framework/introduction/app/Module.java diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/introduction/app/controllers/AsyncController.java similarity index 100% rename from play-framework/student-api/app/controllers/AsyncController.java rename to play-framework/introduction/app/controllers/AsyncController.java diff --git a/play-framework/student-api/app/controllers/CountController.java b/play-framework/introduction/app/controllers/CountController.java similarity index 100% rename from play-framework/student-api/app/controllers/CountController.java rename to play-framework/introduction/app/controllers/CountController.java diff --git a/play-framework/student-api/app/controllers/HomeController.java b/play-framework/introduction/app/controllers/HomeController.java similarity index 100% rename from play-framework/student-api/app/controllers/HomeController.java rename to play-framework/introduction/app/controllers/HomeController.java diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/introduction/app/controllers/StudentController.java similarity index 100% rename from play-framework/student-api/app/controllers/StudentController.java rename to play-framework/introduction/app/controllers/StudentController.java diff --git a/play-framework/student-api/app/filters/ExampleFilter.java b/play-framework/introduction/app/filters/ExampleFilter.java similarity index 100% rename from play-framework/student-api/app/filters/ExampleFilter.java rename to play-framework/introduction/app/filters/ExampleFilter.java diff --git a/play-framework/student-api/app/models/Student.java b/play-framework/introduction/app/models/Student.java similarity index 100% rename from play-framework/student-api/app/models/Student.java rename to play-framework/introduction/app/models/Student.java diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/introduction/app/models/StudentStore.java similarity index 100% rename from play-framework/student-api/app/models/StudentStore.java rename to play-framework/introduction/app/models/StudentStore.java diff --git a/play-framework/student-api/app/services/ApplicationTimer.java b/play-framework/introduction/app/services/ApplicationTimer.java similarity index 100% rename from play-framework/student-api/app/services/ApplicationTimer.java rename to play-framework/introduction/app/services/ApplicationTimer.java diff --git a/play-framework/student-api/app/services/AtomicCounter.java b/play-framework/introduction/app/services/AtomicCounter.java similarity index 100% rename from play-framework/student-api/app/services/AtomicCounter.java rename to play-framework/introduction/app/services/AtomicCounter.java diff --git a/play-framework/student-api/app/services/Counter.java b/play-framework/introduction/app/services/Counter.java similarity index 100% rename from play-framework/student-api/app/services/Counter.java rename to play-framework/introduction/app/services/Counter.java diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/introduction/app/util/Util.java similarity index 100% rename from play-framework/student-api/app/util/Util.java rename to play-framework/introduction/app/util/Util.java diff --git a/play-framework/student-api/app/views/index.scala.html b/play-framework/introduction/app/views/index.scala.html similarity index 100% rename from play-framework/student-api/app/views/index.scala.html rename to play-framework/introduction/app/views/index.scala.html diff --git a/play-framework/student-api/app/views/main.scala.html b/play-framework/introduction/app/views/main.scala.html similarity index 100% rename from play-framework/student-api/app/views/main.scala.html rename to play-framework/introduction/app/views/main.scala.html diff --git a/play-framework/student-api/bin/activator b/play-framework/introduction/bin/activator similarity index 100% rename from play-framework/student-api/bin/activator rename to play-framework/introduction/bin/activator diff --git a/play-framework/student-api/bin/activator.bat b/play-framework/introduction/bin/activator.bat similarity index 100% rename from play-framework/student-api/bin/activator.bat rename to play-framework/introduction/bin/activator.bat diff --git a/play-framework/student-api/build.sbt b/play-framework/introduction/build.sbt similarity index 100% rename from play-framework/student-api/build.sbt rename to play-framework/introduction/build.sbt diff --git a/play-framework/student-api/conf/application.conf b/play-framework/introduction/conf/application.conf similarity index 100% rename from play-framework/student-api/conf/application.conf rename to play-framework/introduction/conf/application.conf diff --git a/play-framework/student-api/conf/logback.xml b/play-framework/introduction/conf/logback.xml similarity index 100% rename from play-framework/student-api/conf/logback.xml rename to play-framework/introduction/conf/logback.xml diff --git a/play-framework/student-api/conf/routes b/play-framework/introduction/conf/routes similarity index 100% rename from play-framework/student-api/conf/routes rename to play-framework/introduction/conf/routes diff --git a/play-framework/student-api/libexec/activator-launch-1.3.10.jar b/play-framework/introduction/libexec/activator-launch-1.3.10.jar similarity index 100% rename from play-framework/student-api/libexec/activator-launch-1.3.10.jar rename to play-framework/introduction/libexec/activator-launch-1.3.10.jar diff --git a/play-framework/student-api/project/build.properties b/play-framework/introduction/project/build.properties similarity index 100% rename from play-framework/student-api/project/build.properties rename to play-framework/introduction/project/build.properties diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/introduction/project/plugins.sbt similarity index 100% rename from play-framework/student-api/project/plugins.sbt rename to play-framework/introduction/project/plugins.sbt diff --git a/play-framework/student-api/public/images/favicon.png b/play-framework/introduction/public/images/favicon.png similarity index 100% rename from play-framework/student-api/public/images/favicon.png rename to play-framework/introduction/public/images/favicon.png diff --git a/play-framework/student-api/public/javascripts/hello.js b/play-framework/introduction/public/javascripts/hello.js similarity index 100% rename from play-framework/student-api/public/javascripts/hello.js rename to play-framework/introduction/public/javascripts/hello.js diff --git a/play-framework/student-api/public/stylesheets/main.css b/play-framework/introduction/public/stylesheets/main.css similarity index 100% rename from play-framework/student-api/public/stylesheets/main.css rename to play-framework/introduction/public/stylesheets/main.css diff --git a/play-framework/introduction/test/ApplicationTest.java b/play-framework/introduction/test/ApplicationTest.java new file mode 100644 index 0000000000..1133978e9a --- /dev/null +++ b/play-framework/introduction/test/ApplicationTest.java @@ -0,0 +1,172 @@ + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +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 static play.test.Helpers.*; + +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/routing-in-play/.gitignore b/play-framework/routing-in-play/.gitignore similarity index 100% rename from routing-in-play/.gitignore rename to play-framework/routing-in-play/.gitignore diff --git a/routing-in-play/LICENSE b/play-framework/routing-in-play/LICENSE similarity index 100% rename from routing-in-play/LICENSE rename to play-framework/routing-in-play/LICENSE diff --git a/routing-in-play/README b/play-framework/routing-in-play/README similarity index 100% rename from routing-in-play/README rename to play-framework/routing-in-play/README diff --git a/routing-in-play/app/Filters.java b/play-framework/routing-in-play/app/Filters.java similarity index 100% rename from routing-in-play/app/Filters.java rename to play-framework/routing-in-play/app/Filters.java diff --git a/routing-in-play/app/Module.java b/play-framework/routing-in-play/app/Module.java similarity index 100% rename from routing-in-play/app/Module.java rename to play-framework/routing-in-play/app/Module.java diff --git a/routing-in-play/app/controllers/HomeController.java b/play-framework/routing-in-play/app/controllers/HomeController.java similarity index 100% rename from routing-in-play/app/controllers/HomeController.java rename to play-framework/routing-in-play/app/controllers/HomeController.java diff --git a/routing-in-play/app/filters/ExampleFilter.java b/play-framework/routing-in-play/app/filters/ExampleFilter.java similarity index 100% rename from routing-in-play/app/filters/ExampleFilter.java rename to play-framework/routing-in-play/app/filters/ExampleFilter.java diff --git a/routing-in-play/app/services/ApplicationTimer.java b/play-framework/routing-in-play/app/services/ApplicationTimer.java similarity index 100% rename from routing-in-play/app/services/ApplicationTimer.java rename to play-framework/routing-in-play/app/services/ApplicationTimer.java diff --git a/routing-in-play/app/services/AtomicCounter.java b/play-framework/routing-in-play/app/services/AtomicCounter.java similarity index 100% rename from routing-in-play/app/services/AtomicCounter.java rename to play-framework/routing-in-play/app/services/AtomicCounter.java diff --git a/routing-in-play/app/services/Counter.java b/play-framework/routing-in-play/app/services/Counter.java similarity index 100% rename from routing-in-play/app/services/Counter.java rename to play-framework/routing-in-play/app/services/Counter.java diff --git a/routing-in-play/app/views/index.scala.html b/play-framework/routing-in-play/app/views/index.scala.html similarity index 100% rename from routing-in-play/app/views/index.scala.html rename to play-framework/routing-in-play/app/views/index.scala.html diff --git a/routing-in-play/app/views/main.scala.html b/play-framework/routing-in-play/app/views/main.scala.html similarity index 100% rename from routing-in-play/app/views/main.scala.html rename to play-framework/routing-in-play/app/views/main.scala.html diff --git a/routing-in-play/bin/activator b/play-framework/routing-in-play/bin/activator similarity index 100% rename from routing-in-play/bin/activator rename to play-framework/routing-in-play/bin/activator diff --git a/routing-in-play/bin/activator.bat b/play-framework/routing-in-play/bin/activator.bat similarity index 100% rename from routing-in-play/bin/activator.bat rename to play-framework/routing-in-play/bin/activator.bat diff --git a/routing-in-play/build.sbt b/play-framework/routing-in-play/build.sbt similarity index 100% rename from routing-in-play/build.sbt rename to play-framework/routing-in-play/build.sbt diff --git a/routing-in-play/conf/application.conf b/play-framework/routing-in-play/conf/application.conf similarity index 100% rename from routing-in-play/conf/application.conf rename to play-framework/routing-in-play/conf/application.conf diff --git a/routing-in-play/conf/logback.xml b/play-framework/routing-in-play/conf/logback.xml similarity index 100% rename from routing-in-play/conf/logback.xml rename to play-framework/routing-in-play/conf/logback.xml diff --git a/routing-in-play/conf/routes b/play-framework/routing-in-play/conf/routes similarity index 100% rename from routing-in-play/conf/routes rename to play-framework/routing-in-play/conf/routes diff --git a/routing-in-play/libexec/activator-launch-1.3.10.jar b/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar similarity index 100% rename from routing-in-play/libexec/activator-launch-1.3.10.jar rename to play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar diff --git a/routing-in-play/project/build.properties b/play-framework/routing-in-play/project/build.properties similarity index 100% rename from routing-in-play/project/build.properties rename to play-framework/routing-in-play/project/build.properties diff --git a/routing-in-play/project/plugins.sbt b/play-framework/routing-in-play/project/plugins.sbt similarity index 100% rename from routing-in-play/project/plugins.sbt rename to play-framework/routing-in-play/project/plugins.sbt diff --git a/routing-in-play/public/images/favicon.png b/play-framework/routing-in-play/public/images/favicon.png similarity index 100% rename from routing-in-play/public/images/favicon.png rename to play-framework/routing-in-play/public/images/favicon.png diff --git a/routing-in-play/public/javascripts/hello.js b/play-framework/routing-in-play/public/javascripts/hello.js similarity index 100% rename from routing-in-play/public/javascripts/hello.js rename to play-framework/routing-in-play/public/javascripts/hello.js diff --git a/routing-in-play/public/stylesheets/main.css b/play-framework/routing-in-play/public/stylesheets/main.css similarity index 100% rename from routing-in-play/public/stylesheets/main.css rename to play-framework/routing-in-play/public/stylesheets/main.css diff --git a/routing-in-play/test/ApplicationTest.java b/play-framework/routing-in-play/test/ApplicationTest.java similarity index 100% rename from routing-in-play/test/ApplicationTest.java rename to play-framework/routing-in-play/test/ApplicationTest.java diff --git a/routing-in-play/test/IntegrationTest.java b/play-framework/routing-in-play/test/IntegrationTest.java similarity index 100% rename from routing-in-play/test/IntegrationTest.java rename to play-framework/routing-in-play/test/IntegrationTest.java diff --git a/pom.xml b/pom.xml index 466e2fe939..705b66bf16 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,5 @@ - + + 4.0.0 com.baeldung parent-modules @@ -14,97 +14,110 @@ - assertj + annotations apache-cxf - - autovalue-tutorial + apache-fop + assertj + autovalue cdi - core-java - core-java-8 - couchbase-sdk + core-java + couchbase-sdk - dozer - dependency-injection deltaspike + dozer + + feign + flyway - patterns - feign-client + gson guava guava18 guava19 handling-spring-static-resources + hazelcast httpclient + hystrix immutables jackson + java-cassandra javaxval + jee7 jjwt - jooq-spring jpa-storedprocedure - json + jsf json-path + json junit5 - jee7schedule - log4j + lombok + mapstruct mockito mocks - mutation-testing orika + patterns + querydsl + redis rest-assured rest-testing resteasy - spring-all + selenium-junit-testng spring-akka + spring-all spring-apache-camel spring-autowire spring-batch spring-boot + spring-cloud-data-flow + spring-cloud + spring-core spring-cucumber spring-data-cassandra spring-data-couchbase-2 + spring-data-dynamodb spring-data-elasticsearch - spring-data-neo4j spring-data-mongodb + spring-data-neo4j spring-data-redis spring-data-rest + spring-dispatcher-servlet spring-exceptions spring-freemarker spring-hibernate3 spring-hibernate4 - spring-jpa + spring-integration spring-jms + spring-jooq + spring-jpa spring-katharsis spring-mockito spring-mvc-java spring-mvc-no-xml - spring-mvc-xml spring-mvc-tiles + spring-mvc-velocity + spring-mvc-web-vs-initializer + spring-mvc-xml spring-openid spring-protobuf spring-quartz - spring-spel - spring-rest spring-rest-angular spring-rest-docs - spring-cloud - spring-cloud-data-flow - + spring-rest spring-security-basic-auth spring-security-custom-permission spring-security-mvc-custom @@ -113,26 +126,26 @@ spring-security-mvc-login spring-security-mvc-persisted-remember-me spring-security-mvc-session - spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom spring-security-rest-digest-auth spring-security-rest-full + spring-security-rest spring-security-x509 - spring-thymeleaf - spring-zuul - spring-mvc-velocity spring-session + spring-spel + spring-thymeleaf + spring-userservice + spring-zuul - jsf - xml - lombok - redis + testing wicket - xstream - java-cassandra - annotations - - + xml + xmlunit2 + xstream + pdf + + + \ No newline at end of file diff --git a/printscreen/pom.xml b/printscreen/pom.xml deleted file mode 100644 index ddb813a7a2..0000000000 --- a/printscreen/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - 4.0.0 - - com.baeldung - corejava-printscreen - 1.0-SNAPSHOT - jar - - How to Print Screen in Java - https://github.com/eugenp/tutorials - - - UTF-8 - 4.12 - - - - - junit - junit - ${junit.version} - test - - - diff --git a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java b/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java deleted file mode 100644 index d33761932f..0000000000 --- a/printscreen/src/main/java/org/baeldung/corejava/Screenshot.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.corejava;; - -import javax.imageio.ImageIO; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.io.File; - -public class Screenshot { - - private String filePath; - private String filenamePrefix; - private String fileType; - private int timeToWait; - - public Screenshot(String filePath, String filenamePrefix, - String fileType, int timeToWait) { - this.filePath = filePath; - this.filenamePrefix = filenamePrefix; - this.fileType = fileType; - this.timeToWait = timeToWait; - } - - public void getScreenshot() throws Exception { - Thread.sleep(timeToWait); - Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); - Robot robot = new Robot(); - BufferedImage img = robot.createScreenCapture(rectangle); - ImageIO.write(img, fileType, setupFileNamePath()); - } - - private File setupFileNamePath() { - return new File(filePath + filenamePrefix + "." + fileType); - } - - private Rectangle getScreenSizedRectangle(final Dimension d) { - return new Rectangle(0, 0, d.width, d.height); - } -} diff --git a/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java b/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java deleted file mode 100644 index 588c2eea78..0000000000 --- a/printscreen/src/test/java/org/baeldung/corejava/ScreenshotTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.corejava; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; - -import static org.junit.Assert.*; - - -public class ScreenshotTest { - - private Screenshot screenshot; - private String filePath; - private String fileName; - private String fileType; - private File file; - - @Before - public void setUp() throws Exception { - filePath = ""; - fileName = "Screenshot"; - fileType = "jpg"; - file = new File(filePath + fileName + "." + fileType); - screenshot = new Screenshot(filePath, fileName, fileType, 2000); - } - - @Test - public void testGetScreenshot() throws Exception { - screenshot.getScreenshot(); - assertTrue(file.exists()); - } - - @After - public void tearDown() throws Exception { - file.delete(); - } -} \ No newline at end of file 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/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-testing/pom.xml b/rest-testing/pom.xml index 819e8de8a5..90c160af15 100644 --- a/rest-testing/pom.xml +++ b/rest-testing/pom.xml @@ -148,12 +148,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 + + + + **/*UnitTest.java + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + json + + + + + + + + 2.7.8 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/resteasy/pom.xml b/resteasy/pom.xml index ec9e87b0d1..04e8576e1f 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -10,6 +10,8 @@ 3.0.14.Final + 2.19.1 + 1.6.0 @@ -23,6 +25,35 @@ 1.8 + + 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 + + + + @@ -73,5 +104,66 @@ + + + live + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + \ No newline at end of file diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java similarity index 61% rename from resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java rename to resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java index ef18b0f23f..7e709edb96 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java @@ -1,7 +1,15 @@ package com.baeldung.server; -import com.baeldung.client.ServicesInterface; -import com.baeldung.model.Movie; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; @@ -14,18 +22,13 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.junit.Before; import org.junit.Test; -import javax.naming.NamingException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Locale; -public class RestEasyClientTest { +import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; - public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest"); +public class RestEasyClientLiveTest { + + public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @@ -35,22 +38,22 @@ public class RestEasyClientTest { jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) { + final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) { + final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Test is going to die ...", e); } } @@ -58,41 +61,41 @@ public class RestEasyClientTest { @Test public void testListAllMovies() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - List movies = proxy.listMovies(); + final List movies = proxy.listMovies(); System.out.println(movies); } @Test public void testMovieByImdbId() { - String transformerImdbId = "tt0418279"; + final String transformerImdbId = "tt0418279"; - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = proxy.addMovie(transformerMovie); + final Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); - Movie movies = proxy.movieByImdbId(transformerImdbId); + final Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); } @Test public void testAddMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -109,17 +112,15 @@ public class RestEasyClientTest { @Test public void testAddMovieMultiConnection() { - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(cm) - .build(); - ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); - ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); + final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); + final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response batmanResponse = proxy.addMovie(batmanMovie); - Response transformerResponse = proxy.addMovie(transformerMovie); + final Response batmanResponse = proxy.addMovie(batmanMovie); + final Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); @@ -132,16 +133,14 @@ public class RestEasyClientTest { transformerResponse.close(); cm.close(); - - } @Test public void testDeleteMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -159,9 +158,9 @@ public class RestEasyClientTest { @Test public void testUpdateMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index bf5a082fba..cc96ea8529 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -20,29 +20,50 @@ 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 selenium-java - 2.53.1 + 3.0.1 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..58d47c0162 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,24 @@ package main.java.com.baeldung.selenium; +import java.util.List; +import java.util.NoSuchElementException; +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() { + System.setProperty("webdriver.firefox.marionette", "C:\\selenium\\geckodriver.exe"); webDriver = new FirefoxDriver(); + webDriver.manage().window().maximize(); + webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); webDriver.get(url); } @@ -21,4 +30,32 @@ public class SeleniumExample { return webDriver.getTitle(); } + public void getAboutBaeldungPage() { + closeOverlay(); + clickAboutLink(); + clickAboutUsLink(); + } + + private void closeOverlay() { + List webElementList = webDriver.findElements(By.tagName("a")); + try { + if (webElementList != null && !webElementList.isEmpty()) { + webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click(); + } + } catch (NoSuchElementException exception) { + exception.printStackTrace(); + } + } + + 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/README.md b/sockets/README.md deleted file mode 100644 index ad8811ee80..0000000000 --- a/sockets/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) 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/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/sockets/src/main/java/com/baeldung/socket/EchoClient.java deleted file mode 100644 index e8ec97c80a..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoClient.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.socket; - -import java.io.*; -import java.net.*; - -public class EchoClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - System.out.print(e); - } - - } - - public String sendMessage(String msg) { - try { - out.println(msg); - String resp = in.readLine(); - return resp; - } catch (Exception e) { - return null; - } - } - - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } -} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java deleted file mode 100644 index 2ece1ceebe..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class EchoMultiServer { - private ServerSocket serverSocket; - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - while (true) - new EchoClientHandler(serverSocket.accept()).run(); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - stop(); - } - - } - - public void stop() { - try { - - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - private static class EchoClientHandler extends Thread { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public EchoClientHandler(Socket socket) { - this.clientSocket = socket; - } - - public void run() { - try { - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("bye"); - break; - } - out.println(inputLine); - } - - in.close(); - out.close(); - clientSocket.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public static void main(String[] args) { - EchoMultiServer server = new EchoMultiServer(); - server.start(5555); - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/sockets/src/main/java/com/baeldung/socket/EchoServer.java deleted file mode 100644 index 3607afa7f5..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoServer.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class EchoServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("good bye"); - break; - } - out.println(inputLine); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static void main(String[] args) { - EchoServer server = new EchoServer(); - server.start(4444); - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/sockets/src/main/java/com/baeldung/socket/GreetClient.java deleted file mode 100644 index 7252827c87..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/GreetClient.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.socket; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; - -public class GreetClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - - } - - } - - public String sendMessage(String msg) { - try { - out.println(msg); - String resp = in.readLine(); - return resp; - } catch (Exception e) { - return null; - } - } - - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/sockets/src/main/java/com/baeldung/socket/GreetServer.java deleted file mode 100644 index 8bf675c7b9..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/GreetServer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class GreetServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String greeting = in.readLine(); - if ("hello server".equals(greeting)) - out.println("hello client"); - else - out.println("unrecognised greeting"); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - public static void main(String[] args) { - GreetServer server=new GreetServer(); - server.start(6666); - } - -} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java deleted file mode 100644 index 19a59c211c..0000000000 --- a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.socket; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - -public class EchoMultiTest { - - { - Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555)); - } - - - @Test - public void givenClient1_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - - @Test - public void givenClient2_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - - @Test - public void givenClient3_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - -} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/sockets/src/test/java/com/baeldung/socket/EchoTest.java deleted file mode 100644 index 0f0c02e4d8..0000000000 --- a/sockets/src/test/java/com/baeldung/socket/EchoTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.socket; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - -public class EchoTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444)); - } - - EchoClient client = new EchoClient(); - - @Before - public void init() { - client.startConnection("127.0.0.1", 4444); - } - - @Test - public void givenClient_whenServerEchosMessage_thenCorrect() { - - String resp1 = client.sendMessage("hello"); - String resp2 = client.sendMessage("world"); - String resp3 = client.sendMessage("!"); - String resp4 = client.sendMessage("."); - assertEquals("hello", resp1); - assertEquals("world", resp2); - assertEquals("!", resp3); - assertEquals("good bye", resp4); - } - - @After - public void tearDown() { - client.stopConnection(); - } - -} 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/test/java/org/baeldung/akka/SpringAkkaTest.java b/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java similarity index 94% rename from spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java rename to spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java index e5351e9d0f..c5da0f747e 100644 --- a/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaTest.java +++ b/spring-akka/src/test/java/org/baeldung/akka/SpringAkkaIntegrationTest.java @@ -20,7 +20,7 @@ import static akka.pattern.Patterns.ask; import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; @ContextConfiguration(classes = AppConfiguration.class) -public class SpringAkkaTest extends AbstractJUnit4SpringContextTests { +public class SpringAkkaIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired private ActorSystem system; diff --git a/spring-all/README.md b/spring-all/README.md index aae98440f3..90ae69300a 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide To Running Logic on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) +- [Introduction To Ehcache](http://www.baeldung.com/ehcache) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 003cdacc2c..23f2531b51 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -224,7 +224,7 @@ maven-surefire-plugin - + **/*IntegrationTest.java @@ -232,31 +232,45 @@ - - 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.3.1.RELEASE diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web.xml index 4e0e7a231c..3ac9e9ed8c 100644 --- a/spring-all/src/main/webapp/WEB-INF/web.xml +++ b/spring-all/src/main/webapp/WEB-INF/web.xml @@ -9,11 +9,11 @@ org.springframework.web.servlet.DispatcherServlet - 1 contextConfigLocation /WEB-INF/test-mvc.xml + 1 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 95% 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 84bc3a8033..82c8704360 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -21,7 +21,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) -public class ControllerAnnotationTest { +public class ControllerAnnotationIntegrationTest { private MockMvc mockMvc; 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 98% 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 47915b8ce9..8e8a021530 100644 --- a/spring-all/src/test/java/org/baeldung/controller/ControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/ControllerIntegrationTest.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "classpath:test-mvc.xml" }) -public class ControllerTest { +public class ControllerIntegrationTest { private MockMvc mockMvc; 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 index 875fd2a25e..ab7aebf7a1 100644 --- a/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java +++ b/spring-all/src/test/java/org/baeldung/ehcache/SquareCalculatorTest.java @@ -1,20 +1,20 @@ package org.baeldung.ehcache; -import static org.junit.Assert.*; - 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 { - SquaredCalculator squaredCalculator = new SquaredCalculator(); - CacheHelper cacheHelper = new CacheHelper(); + private SquaredCalculator squaredCalculator = new SquaredCalculator(); + private CacheHelper cacheHelper = new CacheHelper(); @Before public void setup() { squaredCalculator.setCache(cacheHelper); - } @Test @@ -22,7 +22,7 @@ public class SquareCalculatorTest { for (int i = 10; i < 15; i++) { assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); System.out.println("Square value of " + i + " is: " - + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + + squaredCalculator.getSquareValueOfNumber(i) + "\n"); } } @@ -31,13 +31,13 @@ public class SquareCalculatorTest { for (int i = 10; i < 15; i++) { assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); System.out.println("Square value of " + i + " is: " - + squaredCalculator.getSquareValueOfNumber(i) + "\n"); + + 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"); + + 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/spring43/attributeannotations/AttributeAnnotationTest.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationIntegrationTest.java similarity index 94% 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 5162a067d7..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; 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 94% 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 75d828c3d3..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; 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 85% 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 3edf693a13..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 @@ -8,7 +8,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class }) -public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests { +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/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 97% 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 ecf14f0d6c..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; 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/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/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceIntegrationTest.java similarity index 94% 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 50e89fcc55..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 @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) -public class FooServiceTest { +public class FooServiceIntegrationTest { @Autowired FooService fooService; diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 5281b9b2c0..a2555259b0 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -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/test/java/com/baeldung/WebjarsdemoApplicationTests.java b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java similarity index 89% rename from spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java rename to spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java index c43b13ea0b..3558682b97 100644 --- a/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationTests.java +++ b/spring-boot/src/test/java/com/baeldung/WebjarsdemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ 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() { 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 94% 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 c0fc1befd3..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; diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 97% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java rename to spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index 1255180e44..3c5444942c 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -26,7 +26,7 @@ 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; 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 f4ce158661..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; 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 96% 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 ba0da968ad..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; diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 2ddb9d85a3..99e57d4c20 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -67,8 +67,17 @@ org.springframework.boot spring-boot-maven-plugin - - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java similarity index 86% rename from spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java rename to spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java index 5f18ec75c4..f8dfdec197 100644 --- a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class BatchJobApplicationTests { +public class BatchJobApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index 94c4106d6f..451a58e12a 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -62,8 +62,53 @@ 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-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java new file mode 100644 index 0000000000..bb8660b816 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowServerApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index a074fef88f..31d3dce507 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -62,8 +62,18 @@ org.springframework.boot spring-boot-maven-plugin - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + 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..92a8488c7d --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/spring-shell.log @@ -0,0 +1,2 @@ +// dataflow 1.2.0.RELEASE log opened at 2016-10-20 13:13:20 +// dataflow 1.2.0.RELEASE log opened at 2016-10-24 16:51:17 diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java similarity index 85% rename from spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java rename to spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java index f853e29244..5ab3292388 100644 --- a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class DataFlowServerApplicationTests { +public class DataFlowShellApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 8415d95373..db488c05ef 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -1,62 +1,105 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.baeldung.spring.cloud - log-sink - 0.0.1-SNAPSHOT - jar + org.baeldung.spring.cloud + log-sink + 0.0.1-SNAPSHOT + jar - log-sink - Demo project for Spring Boot + log-sink + Demo project for Spring Boot - - org.springframework.boot - spring-boot-starter-parent - 1.4.0.RELEASE - - + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + - - - org.springframework.cloud - spring-cloud-starter-stream-rabbit - + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + - - org.springframework.boot - spring-boot-starter-test - test - - + + org.springframework.boot + spring-boot-starter-test + test + + - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.SR5 - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + 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-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java similarity index 86% rename from spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java rename to spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java index 7e2bc1cb37..b362d72705 100644 --- a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class DataFlowShellApplicationTests { +public class LogSinkApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index bc2efe7754..8277c9c836 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -49,14 +49,57 @@ - - - - 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-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java new file mode 100644 index 0000000000..9bd0fd8c24 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeProcessorApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java deleted file mode 100644 index 875346f9db..0000000000 --- a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TimeProcessorApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 587b782227..086d761f78 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -49,14 +49,57 @@ - - - - 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-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java similarity index 85% rename from spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java rename to spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java index 9f88c7f632..6d71a785a3 100644 --- a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class LogSinkApplicationTests { +public class TimeSourceApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java deleted file mode 100644 index 61fd8323d2..0000000000 --- a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TimeSourceApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java index f008dff90e..e607144f11 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/bootstrap/config/SecurityConfig.java @@ -1,6 +1,8 @@ package com.baeldung.spring.cloud.bootstrap.config; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @@ -9,11 +11,19 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests().anyRequest().hasRole("SYSTEM").and() - .httpBasic().and() - .csrf().disable(); - } + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ + auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .anyRequest().hasRole("SYSTEM") + .and() + .httpBasic() + .and() + .csrf() + .disable(); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index b8cb66e3e4..b559da6394 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -15,37 +15,51 @@ import org.springframework.security.config.http.SessionCreationPolicy; @Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ + auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) + .and() + .requestMatchers() + .antMatchers("/eureka/**") + .and() + .authorizeRequests() + .antMatchers("/eureka/**").hasRole("SYSTEM") + .anyRequest().denyAll() + .and() + .httpBasic() + .and() + .csrf() + .disable(); + } + + @Configuration + //no order tag means this is the last security filter to be evaluated + public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication(); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and() - .requestMatchers().antMatchers("/eureka/**").and() - .authorizeRequests() - .antMatchers("/eureka/**").hasRole("SYSTEM") - .anyRequest().denyAll().and() - .httpBasic().and() - .csrf().disable(); - } - - @Configuration - //no order tag means this is the last security filter to be evaluated - public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() - .httpBasic().disable() - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") - .antMatchers("/info", "/health").authenticated() - .anyRequest().denyAll().and() - .csrf().disable(); - } + @Override protected void configure(HttpSecurity http) throws Exception { + http + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.NEVER) + .and() + .httpBasic() + .disable() + .authorizeRequests() + .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") + .antMatchers("/info","/health").authenticated() + .anyRequest().denyAll() + .and() + .csrf() + .disable(); } + } } diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java index 417b61d238..60dccf9042 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/SecurityConfig.java @@ -11,23 +11,27 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("user").password("password").roles("USER").and() - .withUser("admin").password("admin").roles("ADMIN"); - } + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user").password("password").roles("USER") + .and() + .withUser("admin").password("admin").roles("ADMIN"); + } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/resource/hello/cloud").permitAll() - .antMatchers("/eureka/**").hasRole("ADMIN") - .anyRequest().authenticated().and() - .formLogin().and() - .logout().permitAll() - .logoutSuccessUrl("/resource/hello/cloud").permitAll().and() - .csrf().disable(); - } + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/resource/hello/cloud").permitAll() + .antMatchers("/eureka/**").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .formLogin() + .and() + .logout().permitAll() + .logoutSuccessUrl("/resource/hello/cloud").permitAll() + .and() + .csrf() + .disable(); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java index 813956676e..0b0de6ec20 100644 --- a/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/bootstrap/resource/SecurityConfig.java @@ -1,6 +1,8 @@ package com.baeldung.spring.cloud.bootstrap.resource; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @@ -9,15 +11,23 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .httpBasic().disable() - .authorizeRequests() - .antMatchers("/hello/cloud").permitAll() - .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") - .antMatchers("/hello/admin").hasRole("ADMIN") - .anyRequest().authenticated().and() - .csrf().disable(); - } + @Autowired + public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { + //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere + auth.inMemoryAuthentication(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .disable() + .authorizeRequests() + .antMatchers("/hello/cloud").permitAll() + .antMatchers("/hello/user").hasAnyRole("USER", "ADMIN") + .antMatchers("/hello/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .csrf() + .disable(); + } } diff --git a/spring-cloud/spring-cloud-config/client-config/config-client-production.properties b/spring-cloud/spring-cloud-config/client-config/config-client-production.properties deleted file mode 100644 index cd2e14fcc3..0000000000 --- a/spring-cloud/spring-cloud-config/client-config/config-client-production.properties +++ /dev/null @@ -1 +0,0 @@ -user.role=User diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index 0ef4b35581..2c4b748e8a 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -6,49 +6,30 @@ com.baeldung.spring.cloud spring-cloud-config - 0.0.1-SNAPSHOT + 1.0-SNAPSHOT client - jar - - client - Demo project for Spring Cloud Config Client - - - UTF-8 - UTF-8 - 1.8 - org.springframework.cloud spring-cloud-starter-config + 1.2.0.RELEASE org.springframework.boot spring-boot-starter-web + ${org.springframework.boot.version} org.springframework.boot spring-boot-starter-test + ${org.springframework.boot.version} test - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.BUILD-SNAPSHOT - pom - import - - - - @@ -57,23 +38,4 @@ - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - diff --git a/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties index 18982a93b5..5dde8baa28 100644 --- a/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties +++ b/spring-cloud/spring-cloud-config/client/src/main/resources/bootstrap.properties @@ -3,3 +3,4 @@ spring.profiles.active=development spring.cloud.config.uri=http://localhost:8888 spring.cloud.config.username=root spring.cloud.config.password=s3cr3t +spring.cloud.config.fail-fast=true diff --git a/spring-cloud/spring-cloud-config/client-config/config-client-development.properties b/spring-cloud/spring-cloud-config/config-repo/config-client-development.properties similarity index 100% rename from spring-cloud/spring-cloud-config/client-config/config-client-development.properties rename to spring-cloud/spring-cloud-config/config-repo/config-client-development.properties diff --git a/spring-cloud/spring-cloud-config/config-repo/config-client-production.properties b/spring-cloud/spring-cloud-config/config-repo/config-client-production.properties new file mode 100644 index 0000000000..ca00f0e390 --- /dev/null +++ b/spring-cloud/spring-cloud-config/config-repo/config-client-production.properties @@ -0,0 +1,2 @@ +user.role=User +user.password=pass diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 8e0e4b8706..7d9fd97ee4 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -5,7 +5,7 @@ com.baeldung.spring.cloud spring-cloud-config - 0.0.1-SNAPSHOT + 1.0-SNAPSHOT pom @@ -16,9 +16,22 @@ org.springframework.boot spring-boot-starter-parent - 1.3.5.RELEASE + 1.4.1.RELEASE + + + + + org.springframework.cloud + spring-cloud-dependencies + Camden.SR1 + pom + import + + + + @@ -36,7 +49,10 @@ - 1.3.5.RELEASE + UTF-8 + UTF-8 + 1.8 + 1.4.1.RELEASE 2.19.1 diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index c3f68854bb..33fac435b1 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -6,77 +6,42 @@ com.baeldung.spring.cloud spring-cloud-config - 0.0.1-SNAPSHOT + 1.0-SNAPSHOT server - server - Demo project for Spring Cloud Config Server - - - UTF-8 - UTF-8 - 1.8 - - org.springframework.cloud spring-cloud-config-server + 1.2.0.RELEASE org.springframework.boot spring-boot-starter-security + ${org.springframework.boot.version} org.springframework.boot spring-boot-starter-web + ${org.springframework.boot.version} org.springframework.boot spring-boot-starter-test + ${org.springframework.boot.version} test - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.BUILD-SNAPSHOT - pom - import - - - - org.springframework.boot spring-boot-maven-plugin + ${org.springframework.boot.version} - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - diff --git a/spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java b/spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java index 4dd34ae3ff..7c5933e509 100644 --- a/spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java +++ b/spring-cloud/spring-cloud-config/server/src/main/java/com/baeldung/spring/cloud/config/server/ConfigServer.java @@ -3,11 +3,9 @@ package com.baeldung.spring.cloud.config.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @SpringBootApplication @EnableConfigServer -@EnableWebSecurity public class ConfigServer { public static void main(String[] args) { SpringApplication.run(ConfigServer.class, args); diff --git a/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties index 2131f3b249..3d4f3bcd47 100644 --- a/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8888 -spring.cloud.config.server.git.uri=https://github.com/eugenp/tutorials/tree/master/spring-cloud-config/client-config -spring.cloud.config.server.git.clone-on-start=false +spring.cloud.config.server.git.uri= +spring.cloud.config.server.git.clone-on-start=true security.user.name=root security.user.password=s3cr3t encrypt.key-store.location=classpath:/config-server.jks 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/dependency-injection/README.md b/spring-core/README.md similarity index 100% rename from dependency-injection/README.md rename to spring-core/README.md 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/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/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/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 98% 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 0bf2c5d673..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"; 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/service/CampusServiceImplTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java similarity index 98% 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 d3982e1ecc..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,7 +18,7 @@ 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; 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 98% 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 c503726377..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"; diff --git a/spring-data-dynamodb/.gitignore b/spring-data-dynamodb/.gitignore new file mode 100644 index 0000000000..e26d6af438 --- /dev/null +++ b/spring-data-dynamodb/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project diff --git a/spring-data-dynamodb/README.MD b/spring-data-dynamodb/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-data-dynamodb/README.MD @@ -0,0 +1 @@ + diff --git a/spring-data-dynamodb/pom.xml b/spring-data-dynamodb/pom.xml new file mode 100644 index 0000000000..11e1366f3e --- /dev/null +++ b/spring-data-dynamodb/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + com.baeldung + spring-boot-dynamodb + 0.0.1-SNAPSHOT + jar + Spring Boot Actuator + This is simple boot application for Spring boot actuator test + + + spring-boot-starter-parent + org.springframework.boot + 1.2.3.RELEASE + + + + + + com.baeldung.Application + UTF-8 + 1.8 + 4.3.1.RELEASE + + + + + + org.springframework.data + spring-data-releasetrain + Gosling-SR1 + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-security + + + + io.dropwizard.metrics + metrics-core + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter + + + com.jayway.jsonpath + json-path + test + + + org.springframework.boot + spring-boot-starter-mail + + + + org.webjars + bootstrap + 3.3.4 + + + + com.amazonaws + aws-java-sdk-dynamodb + 1.11.34 + + + com.github.derjust + spring-data-dynamodb + 4.3.1 + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + + + spring-boot + + + src/main/resources + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/Application.java b/spring-data-dynamodb/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..f5e0e98fd4 --- /dev/null +++ b/spring-data-dynamodb/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung" }) +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java new file mode 100644 index 0000000000..271c1e29ab --- /dev/null +++ b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/config/DynamoDBConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.dynamodb.config; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.dynamodb.repositories") +public class DynamoDBConfig { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${amazon.aws.accesskey}") + private String amazonAWSAccessKey; + + @Value("${amazon.aws.secretkey}") + private String amazonAWSSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(amazonAWSCredentials()); + if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) { + amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint); + } + return amazonDynamoDB; + } + + @Bean + public AWSCredentials amazonAWSCredentials() { + return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); + } + +} diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java new file mode 100644 index 0000000000..3b9b0628dd --- /dev/null +++ b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/model/ProductInfo.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.data.dynamodb.model; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +@DynamoDBTable(tableName = "ProductInfo") +public class ProductInfo { + private String id; + private String msrp; + private String cost; + + public ProductInfo() { + } + + public ProductInfo(String cost, String msrp) { + this.msrp = msrp; + this.cost = cost; + } + + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + public String getId() { + return id; + } + + @DynamoDBAttribute + public String getMsrp() { + return msrp; + } + + @DynamoDBAttribute + public String getCost() { + return cost; + } + + public void setId(String id) { + this.id = id; + } + + public void setMsrp(String msrp) { + this.msrp = msrp; + } + + public void setCost(String cost) { + this.cost = cost; + } +} diff --git a/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java new file mode 100644 index 0000000000..da47f033b6 --- /dev/null +++ b/spring-data-dynamodb/src/main/java/com/baeldung/spring/data/dynamodb/repositories/ProductInfoRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.dynamodb.repositories; + +import com.baeldung.spring.data.dynamodb.model.ProductInfo; +import org.socialsignin.spring.data.dynamodb.repository.EnableScan; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +@EnableScan +public interface ProductInfoRepository extends CrudRepository { + List findById(String id); +} diff --git a/spring-data-dynamodb/src/main/resources/application.properties b/spring-data-dynamodb/src/main/resources/application.properties new file mode 100644 index 0000000000..e6911bc9e7 --- /dev/null +++ b/spring-data-dynamodb/src/main/resources/application.properties @@ -0,0 +1,32 @@ +server.port=8080 +server.contextPath=/springbootapp +management.port=8081 +management.address=127.0.0.1 + +endpoints.shutdown.enabled=true + +endpoints.jmx.domain=Spring Sample Application +endpoints.jmx.uniqueNames=true + +spring.jmx.enabled=true +endpoints.jmx.enabled=true + +## for pretty printing of json when endpoints accessed over HTTP +http.mappers.jsonPrettyPrint=true + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 + +## Spring Security Configurations +security.user.name=admin1 +security.user.password=secret1 +management.security.role=SUPERUSER + +logging.level.org.springframework=INFO + +#AWS Keys +amazon.dynamodb.endpoint=http://localhost:8000/ +amazon.aws.accesskey=test1 +amazon.aws.secretkey=test1 \ No newline at end of file diff --git a/spring-data-dynamodb/src/main/resources/demo.properties b/spring-data-dynamodb/src/main/resources/demo.properties new file mode 100644 index 0000000000..649b64f59b --- /dev/null +++ b/spring-data-dynamodb/src/main/resources/demo.properties @@ -0,0 +1,6 @@ +spring.output.ansi.enabled=never +server.port=7070 + +# Security +security.user.name=admin +security.user.password=password \ No newline at end of file diff --git a/spring-data-dynamodb/src/main/resources/logback.xml b/spring-data-dynamodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..c0bc602910 --- /dev/null +++ b/spring-data-dynamodb/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + diff --git a/spring-data-dynamodb/src/main/resources/templates/index.html b/spring-data-dynamodb/src/main/resources/templates/index.html new file mode 100644 index 0000000000..046d21600a --- /dev/null +++ b/spring-data-dynamodb/src/main/resources/templates/index.html @@ -0,0 +1,19 @@ + + + WebJars Demo + + + + +

+
+ × + Success! It is working as we expected. +
+
+ + + + + + \ No newline at end of file diff --git a/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java b/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java new file mode 100644 index 0000000000..8fe3e96940 --- /dev/null +++ b/spring-data-dynamodb/src/test/java/com/baeldung/spring/data/dynamodb/repository/ProductInfoRepositoryIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.spring.data.dynamodb.repository; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; +import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; +import com.amazonaws.services.dynamodbv2.model.ResourceInUseException; +import com.baeldung.Application; +import com.baeldung.spring.data.dynamodb.model.ProductInfo; +import com.baeldung.spring.data.dynamodb.repositories.ProductInfoRepository; +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.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest +@ActiveProfiles("local") +@TestPropertySource(properties = { "amazon.dynamodb.endpoint=http://localhost:8000/", "amazon.aws.accesskey=test1", "amazon.aws.secretkey=test231" }) +public class ProductInfoRepositoryIntegrationTest { + + private DynamoDBMapper dynamoDBMapper; + + @Autowired + private AmazonDynamoDB amazonDynamoDB; + + @Autowired + ProductInfoRepository repository; + + private static final String EXPECTED_COST = "20"; + private static final String EXPECTED_PRICE = "50"; + + @Before + @Ignore //TODO Remove Ignore annotations when running locally with Local DynamoDB instance + public void setup() throws Exception { + + try { + dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB); + + CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(ProductInfo.class); + + tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); + + amazonDynamoDB.createTable(tableRequest); + } catch (ResourceInUseException e) { + // Do nothing, table already created + } + + // TODO How to handle different environments. i.e. AVOID deleting all entries in ProductInfoion table + dynamoDBMapper.batchDelete((List) repository.findAll()); + } + + @Test + @Ignore //TODO Remove Ignore annotations when running locally with Local DynamoDB instance + public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() { + + ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE); + repository.save(productInfo); + + List result = (List) repository.findAll(); + assertTrue("Not empty", result.size() > 0); + assertTrue("Contains item with expected cost", result.get(0).getCost().equals(EXPECTED_COST)); + } +} diff --git a/spring-data-dynamodb/src/test/resources/application.properties b/spring-data-dynamodb/src/test/resources/application.properties new file mode 100644 index 0000000000..01e8a2e52e --- /dev/null +++ b/spring-data-dynamodb/src/test/resources/application.properties @@ -0,0 +1,7 @@ +spring.mail.host=localhost +spring.mail.port=8025 +spring.mail.properties.mail.smtp.auth=false + +amazon.dynamodb.endpoint=http://localhost:8000/ +amazon.aws.accesskey=key +amazon.aws.secretkey=key2 \ No newline at end of file diff --git a/spring-data-dynamodb/src/test/resources/exception-hibernate.properties b/spring-data-dynamodb/src/test/resources/exception-hibernate.properties new file mode 100644 index 0000000000..cde746acb9 --- /dev/null +++ b/spring-data-dynamodb/src/test/resources/exception-hibernate.properties @@ -0,0 +1,2 @@ +spring.profiles.active=exception +spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext diff --git a/spring-data-dynamodb/src/test/resources/exception.properties b/spring-data-dynamodb/src/test/resources/exception.properties new file mode 100644 index 0000000000..c55e415a3a --- /dev/null +++ b/spring-data-dynamodb/src/test/resources/exception.properties @@ -0,0 +1,6 @@ +# Security +security.user.name=admin +security.user.password=password + +spring.dao.exceptiontranslation.enabled=false +spring.profiles.active=exception \ No newline at end of file diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 42cf8fc740..dcb702ab16 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -20,6 +20,7 @@ 1.7.12 1.1.3 2.0.1.RELEASE + 2.19.1 @@ -86,4 +87,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 + + + + + + + \ No newline at end of file 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 99% 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 863e1e4620..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 @@ -29,7 +29,7 @@ import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchTest { +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 99% 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 ddf0ef4dac..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 @@ -42,7 +42,7 @@ import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) -public class ElasticSearchQueryTest { +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-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/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 97% 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 0e54208c31..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 diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml new file mode 100644 index 0000000000..646db663db --- /dev/null +++ b/spring-dispatcher-servlet/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + + spring-dispatcher-servlet + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + org.springframework + spring-webmvc + 4.3.3.RELEASE + + + org.thymeleaf + thymeleaf-spring4 + 3.0.2.RELEASE + + + org.slf4j + slf4j-api + 1.7.21 + + + org.apache.logging.log4j + log4j-core + 2.7 + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.7 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + false + + + + org.eclipse.jetty + jetty-maven-plugin + 9.3.12.v20160915 + + + / + + + + + + diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java new file mode 100644 index 0000000000..48281c5e5d --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/RootConfiguration.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.dispatcher.servlet; + +import com.baeldung.spring.dispatcher.servlet.models.Task; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.*; + +@Configuration +public class RootConfiguration { + @Bean + public Map> taskList() { + Map> taskMap = new HashMap<>(); + List taskList = new ArrayList<>(); + taskList.add(new Task("Clean the dishes!", new Date())); + taskMap.put("Cid", taskList); + return taskMap; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java new file mode 100644 index 0000000000..016e4a8b4c --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebApplicationInitializer.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.dispatcher.servlet; + +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer { + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + AnnotationConfigWebApplicationContext rootContext = + new AnnotationConfigWebApplicationContext(); + rootContext.register(RootConfiguration.class); + servletContext.addListener(new ContextLoaderListener(rootContext)); + AnnotationConfigWebApplicationContext webContext = + new AnnotationConfigWebApplicationContext(); + webContext.register(WebConfiguration.class); + DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext); + ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", + dispatcherServlet); + servlet.addMapping("/*"); + MultipartConfigElement multipartConfigElement = + new MultipartConfigElement("/tmp"); + servlet.setMultipartConfig(multipartConfigElement); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java new file mode 100644 index 0000000000..419c1a2908 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/WebConfiguration.java @@ -0,0 +1,129 @@ +package com.baeldung.spring.dispatcher.servlet; + +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.ui.context.support.ResourceBundleThemeSource; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.support.StandardServletMultipartResolver; +import org.springframework.web.servlet.HandlerExceptionResolver; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ThemeResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; +import org.springframework.web.servlet.theme.CookieThemeResolver; +import org.springframework.web.servlet.theme.ThemeChangeInterceptor; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +import javax.servlet.ServletContext; +import java.util.Locale; + +@Configuration +@ComponentScan("com.baeldung.spring.dispatcher.servlet.web") +@EnableWebMvc +public class WebConfiguration extends WebMvcConfigurerAdapter { + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry + .addResourceHandler("/public/**") + .addResourceLocations("/public/"); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(localeChangeInterceptor()); + registry.addInterceptor(themeChangeInterceptor()); + } + + @Bean + public ServletContextTemplateResolver templateResolver(ServletContext servletContext) { + ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + return templateResolver; + } + + @Bean + public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver); + return templateEngine; + } + + @Bean + public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine); + return viewResolver; + } + + @Bean + public MessageSource messageSource() { + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + messageSource.setFallbackToSystemLocale(false); + return messageSource; + } + + @Bean + public LocaleResolver localeResolver() { + CookieLocaleResolver localeResolver = new CookieLocaleResolver(); + localeResolver.setDefaultLocale(Locale.ENGLISH); + localeResolver.setCookieName("locale"); + localeResolver.setCookieMaxAge(-1); + return localeResolver; + } + + @Bean + public LocaleChangeInterceptor localeChangeInterceptor() { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + localeChangeInterceptor.setIgnoreInvalidLocale(true); + return localeChangeInterceptor; + } + + @Bean + public ResourceBundleThemeSource themeSource() { + ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); + themeSource.setBasenamePrefix("theme-"); + themeSource.setFallbackToSystemLocale(false); + return themeSource; + } + + @Bean + public ThemeResolver themeResolver() { + CookieThemeResolver themeResolver = new CookieThemeResolver(); + themeResolver.setDefaultThemeName("robotask"); + themeResolver.setCookieName("theme"); + themeResolver.setCookieMaxAge(-1); + return themeResolver; + } + + @Bean + public ThemeChangeInterceptor themeChangeInterceptor() { + ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor(); + themeChangeInterceptor.setParamName("theme"); + return themeChangeInterceptor; + } + + @Bean + public MultipartResolver multipartResolver() { + return new StandardServletMultipartResolver(); + } + + @Bean + public HandlerExceptionResolver handlerExceptionResolver() { + return new ExceptionHandlerExceptionResolver(); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java new file mode 100644 index 0000000000..1d6248650f --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Attachment.java @@ -0,0 +1,58 @@ +package com.baeldung.spring.dispatcher.servlet.models; + +import java.util.UUID; + +public class Attachment { + private String id; + + private String name; + + private String description; + + public Attachment() { + this.id = UUID.randomUUID().toString(); + } + + public Attachment(String name, String description) { + this(); + this.name = name; + this.description = description; + } + + 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 String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Attachment that = (Attachment) o; + return id.equals(that.id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java new file mode 100644 index 0000000000..1e6a533e3a --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/models/Task.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.dispatcher.servlet.models; + +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +public class Task { + private String description; + + @DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm") + private Date due; + + private Set attachments = new HashSet<>(); + + public Task() { + } + + public Task(Date due) { + this.due = due; + } + + public Task(String description, Date due) { + this.description = description; + this.due = due; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getDue() { + return due; + } + + public void setDue(Date due) { + this.due = due; + } + + public Set getAttachments() { + return attachments; + } + + public void setAttachments(Set attachments) { + this.attachments = attachments; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java new file mode 100644 index 0000000000..2521004ff1 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@RequestMapping("/attachments") +public interface AttachmentController { + @GetMapping("/{attachmentId}") + ResponseEntity getAttachment( + @PathVariable("attachmentId") String attachmentId, + @RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java new file mode 100644 index 0000000000..75a15cf657 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/AttachmentControllerImpl.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import com.baeldung.spring.dispatcher.servlet.models.Task; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +import java.net.URLConnection; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +@Controller +public class AttachmentControllerImpl implements AttachmentController { + @Autowired + private Map> taskMap; + + @Override + public ResponseEntity getAttachment( + @PathVariable("attachmentId") String attachmentId, + @RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload + ) { + FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId); + HttpHeaders headers = new HttpHeaders(); + taskMap.values().stream() + .flatMap(Collection::stream) + .flatMap(t -> t.getAttachments().stream()) + .filter(a -> a.getId().equals(attachmentId)) + .findFirst() + .ifPresent(a -> { + headers.add("Content-Disposition", + "attachment; filename=" + a.getName()); + headers.add("Content-Type", forcedDownload ? + MediaType.APPLICATION_OCTET_STREAM_VALUE : + URLConnection.guessContentTypeFromName(a.getName())); + }); + return new ResponseEntity<>(resource, headers, HttpStatus.OK); + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java new file mode 100644 index 0000000000..f25eb601a7 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/GlobalDefaultExceptionHandler.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; + +@ControllerAdvice +public class GlobalDefaultExceptionHandler { + @ExceptionHandler(Exception.class) + public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception { + ModelAndView modelAndView = new ModelAndView(); + modelAndView.addObject("exception", e); + modelAndView.addObject("url", request.getRequestURL()); + modelAndView.setViewName("error"); + return modelAndView; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java new file mode 100644 index 0000000000..5ac39fadb4 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeController.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@RequestMapping("/") +public interface HomeController { + @GetMapping("/*") + String home( + Model model + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java new file mode 100644 index 0000000000..66d869ca67 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/HomeControllerImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import com.baeldung.spring.dispatcher.servlet.models.Task; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Controller +public class HomeControllerImpl implements HomeController { + @Autowired + private Map> taskMap; + + @Override + public String home(Model model) { + List users = taskMap.keySet().stream() + .sorted() + .collect(Collectors.toList()); + model.addAttribute("users", users); + return "home"; + } +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java new file mode 100644 index 0000000000..eff93ffb2f --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskController.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import com.baeldung.spring.dispatcher.servlet.models.Task; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +@RequestMapping("/tasks") +public interface TaskController { + @GetMapping("/{username}/list") + String listTasks( + @PathVariable("username") String username, + Model model + ); + + @GetMapping("/{username}/add") + String addTask( + @PathVariable("username") String username, + Model model + ); + + @PostMapping("/{username}/add") + String addTask( + @PathVariable("username") String username, + @ModelAttribute Task task + ); + + @GetMapping("/{username}/get/{id}") + String getTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + Model model + ); + + @GetMapping("/{username}/get/{id}/attach") + String attachToTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + Model model + ); + + @PostMapping("/{username}/get/{id}/attach") + String attachToTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + @RequestParam("attachment") MultipartFile attachment, + @RequestParam("description") String description + ); +} diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java new file mode 100644 index 0000000000..464e58aa54 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/spring/dispatcher/servlet/web/TaskControllerImpl.java @@ -0,0 +1,111 @@ +package com.baeldung.spring.dispatcher.servlet.web; + +import com.baeldung.spring.dispatcher.servlet.models.Attachment; +import com.baeldung.spring.dispatcher.servlet.models.Task; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + +@Controller +public class TaskControllerImpl implements TaskController { + @Autowired + private Map> taskMap; + + @Override + public String listTasks( + @PathVariable("username") String username, + Model model + ) { + List tasks = taskMap.get(username).stream() + .sorted(Comparator.comparing(Task::getDue)) + .collect(Collectors.toList()); + model.addAttribute("username", username); + model.addAttribute("tasks", tasks); + return "task-list"; + } + + @Override + public String addTask( + @PathVariable("username") String username, + Model model + ) { + model.addAttribute("username", username); + model.addAttribute("task", new Task(new Date())); + return "task-add"; + } + + @Override + public String addTask( + @PathVariable("username") String username, + @ModelAttribute Task task + ) { + List taskList = taskMap.get(username); + if (taskList == null) { + taskList = new ArrayList<>(); + } + taskList.add(task); + taskMap.put(username, taskList); + return "redirect:list"; + } + + @Override + public String getTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + Model model + ) { + Task task = taskMap.get(username).get(id); + model.addAttribute("username", username); + model.addAttribute("id", id); + model.addAttribute("task", task); + return "task-get"; + } + + @Override + public String attachToTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + Model model + ) { + model.addAttribute("username", username); + model.addAttribute("id", id); + return "task-attach"; + } + + @Override + public String attachToTask( + @PathVariable("username") String username, + @PathVariable("id") int id, + @RequestParam("attachment") MultipartFile multipartFile, + @RequestParam("description") String description + ) { + Task task = taskMap.get(username).get(id); + Attachment attachment = new Attachment(multipartFile.getOriginalFilename(), + description); + task.getAttachments().add(attachment); + try (InputStream inputStream = + new BufferedInputStream(multipartFile.getInputStream()); + OutputStream outputStream = + new BufferedOutputStream(Files.newOutputStream( + Paths.get("/tmp", attachment.getId())))) { + byte[] buf = new byte[1024 * 16]; + int len; + while ((len = inputStream.read(buf)) != -1) { + outputStream.write(buf, 0, len); + } + } catch (IOException e) { + throw new RuntimeException("Failed to upload file!", e); + } + return "redirect:./"; + } +} diff --git a/spring-dispatcher-servlet/src/main/resources/log4j2.xml b/spring-dispatcher-servlet/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..fb18e8279a --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/log4j2.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/spring-dispatcher-servlet/src/main/resources/messages.properties b/spring-dispatcher-servlet/src/main/resources/messages.properties new file mode 100644 index 0000000000..c36eb5aa42 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/messages.properties @@ -0,0 +1,22 @@ +home.title=Welcome to TaskTools! +task.add.description=description +task.add.due=due +task.add.header=Adding a task to {0}''s list: +task.add.submit=Submit +task.add.title={0}: task add +task.attach.attachment=attached file +task.attach.description=description +task.attach.header=task #{0}: attach file +task.attach.submit=Submit +task.attach.title=#{0}: Attach file +task.get.attach=Attach file +task.get.attachments=attachments: +task.get.download=Download +task.get.header=task #{0}: +task.get.list=Back +task.get.title={0}: task details +task.list.add-new=Add new +task.list.details=Details +task.list.header={0}''s tasks: +task.list.home=Home +task.list.title={0}: task list diff --git a/spring-dispatcher-servlet/src/main/resources/messages_de.properties b/spring-dispatcher-servlet/src/main/resources/messages_de.properties new file mode 100644 index 0000000000..184b72101c --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/messages_de.properties @@ -0,0 +1,22 @@ +home.title=Willkommen bei TaskTools! +task.add.description=Beschreibung +task.add.due=f\u00e4llig +task.add.header=F\u00fcge eine Aufgabe zu {0}''s Liste hinzu: +task.add.submit=Senden +task.add.title={0}: Task hinzuf\u00fcgen +task.attach.attachment=Angeh\u00e4ngte Datei +task.attach.description=Beschreibung +task.attach.header=Task #{0}: Datei anh\u00e4ngen +task.attach.submit=Senden +task.attach.title=#{0}: Datei anh\u00e4ngen +task.get.attach=Datei anh\u00e4ngen +task.get.attachments=Anh\u00e4nge: +task.get.download=Download +task.get.header=Task #{0}: +task.get.list=Zur\u00fcck +task.get.title={0}: Task Details +task.list.add-new=Neuer Task +task.list.details=Details +task.list.header={0}''s Tasks: +task.list.home=Startseite +task.list.title={0}: Task Liste diff --git a/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties b/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties new file mode 100644 index 0000000000..d2998e2bdf --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/theme-post_it.properties @@ -0,0 +1 @@ +stylesheet=/public/css/themes/post_it.css diff --git a/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties b/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties new file mode 100644 index 0000000000..68fe270b64 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/resources/theme-robotask.properties @@ -0,0 +1 @@ +stylesheet=/public/css/themes/robotask.css diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html new file mode 100644 index 0000000000..8f0f6afca7 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/error.html @@ -0,0 +1,13 @@ + + + + Error + + + + +

Error:

+

+

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html new file mode 100644 index 0000000000..6adec7bb12 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/home.html @@ -0,0 +1,16 @@ + + + + + + + + +

TaskTools

+
    +
  • + +
  • +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html new file mode 100644 index 0000000000..520486f52e --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-add.html @@ -0,0 +1,16 @@ + + + + + + + + +

+
+ + + +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html new file mode 100644 index 0000000000..23246f330b --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-attach.html @@ -0,0 +1,17 @@ + + + + + + + + +

+
+ + + +
+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html new file mode 100644 index 0000000000..e7b35b6780 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-get.html @@ -0,0 +1,28 @@ + + + + + + + + +

+

+

+
+

+
+
+
+ + +
+
+
+

+ + +

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html new file mode 100644 index 0000000000..0671f24ba3 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/WEB-INF/views/task-list.html @@ -0,0 +1,22 @@ + + + + + + + + +

+
    +
  • +

    +

    + +
  • +
+

+ + +

+ + diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/base.css b/spring-dispatcher-servlet/src/main/webapp/public/css/base.css new file mode 100644 index 0000000000..4d3c2597cf --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/base.css @@ -0,0 +1,8 @@ +a.button { + -webkit-appearance: button; + -moz-appearance: button; + appearance: button; + text-decoration: none; + color: #2196f3; + background-color: #e0e0e0; +} diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css new file mode 100644 index 0000000000..578781ec83 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/post_it.css @@ -0,0 +1,8 @@ +@import url('https://fonts.googleapis.com/css?family=Indie+Flower'); + +* { + font-family: 'Indie Flower', sans-serif; + font-size: 18px; + color: #ffeb3b; + background-color: #212121; +} diff --git a/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css new file mode 100644 index 0000000000..8c0121b536 --- /dev/null +++ b/spring-dispatcher-servlet/src/main/webapp/public/css/themes/robotask.css @@ -0,0 +1,8 @@ +@import url('https://fonts.googleapis.com/css?family=Roboto'); + +* { + font-family: Roboto, sans-serif; + font-size: 1em; + color: #212121; + background-color: #fafafa; +} diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 12b7e5de79..6994a518fe 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -194,7 +194,7 @@ ${maven-surefire-plugin.version} - **/*IntegrationTest.java + **/*ManualTest.java diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java index f88138fec2..9597c09568 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java @@ -5,15 +5,15 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - Cause1BeanCreationExceptionIntegrationTest.class - ,Cause2BeanCreationExceptionIntegrationTest.class - ,Cause3BeanCreationExceptionIntegrationTest.class - ,Cause4BeanCreationExceptionIntegrationTest.class - ,Cause5BeanCreationExceptionIntegrationTest.class - ,Cause6BeanCreationExceptionIntegrationTest.class - ,Cause7BeanCreationExceptionIntegrationTest.class - ,Cause8BeanCreationExceptionIntegrationTest.class - ,Cause9BeanCreationExceptionIntegrationTest.class + Cause1BeanCreationExceptionManualTest.class + ,Cause2BeanCreationExceptionManualTest.class + ,Cause3BeanCreationExceptionManualTest.class + ,Cause4BeanCreationExceptionManualTest.class + ,Cause5BeanCreationExceptionManualTest.class + ,Cause6BeanCreationExceptionManualTest.class + ,Cause7BeanCreationExceptionManualTest.class + ,Cause8BeanCreationExceptionManualTest.class + ,Cause9BeanCreationExceptionManualTest.class }) // @formatter:on public class BeanCreationExceptionTestSuite { // diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java index 56d916e25d..350347bb19 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1BeanCreationExceptionIntegrationTest { +public class Cause1BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java index 968e7312de..c2b9561848 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2BeanCreationExceptionIntegrationTest { +public class Cause2BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java index 4730d59334..7b9b49bf58 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3BeanCreationExceptionIntegrationTest { +public class Cause3BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java index b5108c1ab4..3a6e30476c 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause4BeanCreationExceptionIntegrationTest { +public class Cause4BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java index 9a08ec45a1..e69a323f8d 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause5BeanCreationExceptionIntegrationTest { +public class Cause5BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java index 423a0a98a9..30fbd47635 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause6ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause6BeanCreationExceptionIntegrationTest { +public class Cause6BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java index a61e598b41..d832bddf72 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause7ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause7BeanCreationExceptionIntegrationTest { +public class Cause7BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java index 8550f307d5..a9f32b6d1a 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause8ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause8BeanCreationExceptionIntegrationTest { +public class Cause8BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java index ad1ba5f2f1..6af5fb3712 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause9ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause9BeanCreationExceptionIntegrationTest { +public class Cause9BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java index 8de51a4bf0..1580546fa7 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1BeanDefinitionStoreExceptionIntegrationTest { +public class Cause1BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java index 8dbc50cda5..ce0db694dc 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2BeanDefinitionStoreExceptionIntegrationTest { +public class Cause2BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java index 370b67e2fa..c090ac7b5f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3BeanDefinitionStoreExceptionIntegrationTest { +public class Cause3BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java index 0f46481116..056e052359 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1DataIntegrityViolationExceptionIntegrationTest { +public class Cause1DataIntegrityViolationExceptionManualTest { @Autowired private IParentService service; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java index 0ea0dd2f28..e36a027105 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2DataIntegrityViolationExceptionIntegrationTest { +public class Cause2DataIntegrityViolationExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java similarity index 94% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java index 75d5793910..4194e1c9fe 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3DataIntegrityViolationExceptionIntegrationTest { +public class Cause3DataIntegrityViolationExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java index 671b0a473e..7ba9618a77 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1MappingExceptionIntegrationTest { +public class Cause1MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java index eae5ebd9a2..66923fc6a9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2MappingExceptionIntegrationTest { +public class Cause2MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java index d6abe7db4f..e6888d1685 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3MappingExceptionIntegrationTest { +public class Cause3MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java index 864da76e4b..760d082f54 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java @@ -12,7 +12,7 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.Test; -public class Cause4MappingExceptionIntegrationTest { +public class Cause4MappingExceptionManualTest { // tests diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java index 84038e4dcf..b7ed103394 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CannotGetJdbcConnectionExceptionIntegrationTest { +public class CannotGetJdbcConnectionExceptionManualTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java index e62a455dd4..b98a210125 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataIntegrityExceptionIntegrationTest { +public class DataIntegrityExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java similarity index 97% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java index 8a7c237708..122278580f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataRetrievalExceptionIntegrationTest { +public class DataRetrievalExceptionManualTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java index 161bf3252b..4da5f94098 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataSourceLookupExceptionIntegrationTest { +public class DataSourceLookupExceptionManualTest { @Test(expected = DataSourceLookupFailureException.class) public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java index 316efba0b9..fc420acfe9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java @@ -16,7 +16,7 @@ import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class InvalidResourceUsageExceptionIntegrationTest { +public class InvalidResourceUsageExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java index 1a9711b2d6..45ffdf9096 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause1NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java index 90d7317f44..09ed2b4435 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause2NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java index 0e2123b7ff..7dc016a568 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause3NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java index d6c99502d7..91db8210b3 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithJavaIntegrationTest { +public class PropertiesWithJavaManualTest { @Autowired private Environment env; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java index 9fc793fc1b..201e554381 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithXmlConfigOne.class, PropertiesWithXmlConfigTwo.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithMultipleXmlsIntegrationTest { +public class PropertiesWithMultipleXmlsManualTest { @Autowired private Environment env; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java index ff5eaab910..a54dd8a3fb 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithXmlIntegrationTest { +public class PropertiesWithXmlManualTest { @Autowired private Environment env; diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index 9bbdbcecfb..51df4e6647 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -77,7 +77,7 @@ ${jdk.version} ${jdk.version} - true + false diff --git a/spring-freemarker/src/main/webapp/WEB-INF/web.xml b/spring-freemarker/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..a498aef4ad --- /dev/null +++ b/spring-freemarker/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + spring4-freemarker-example + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + \ No newline at end of file diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java index efc6367116..c7f05254cc 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Bar.java @@ -80,7 +80,7 @@ public class Bar implements Serializable { @Column(name = "timestamp") private long timestamp; - @Column(name = "created_date") + @Column(name = "created_date", updatable = false, nullable = false) @CreatedDate private long createdDate; diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml new file mode 100644 index 0000000000..b33f8bd740 --- /dev/null +++ b/spring-integration/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + + com.baeldung.samples.spring.integration + spring-integration + 1.0.0.BUILD-SNAPSHOT + jar + + spring-integration + http://www.springsource.org/spring-integration + + + 2.2.1 + + + + UTF-8 + 2.2.4.RELEASE + 1.2.17 + 4.11 + + + + + repo.springsource.org.milestone + Spring Framework Maven Milestone Repository + https://repo.springsource.org/milestone + + + + + + + maven-eclipse-plugin + 2.9 + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + -Xlint:all + true + true + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + com.baeldung.samples.Main + + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.springframework.integration + spring-integration-core + 4.3.4.RELEASE + + + javax.activation + activation + 1.1.1 + true + + + javax.mail + mail + 1.4.7 + + + log4j + log4j + ${log4j.version} + + + org.springframework.integration + spring-integration-twitter + 4.3.4.RELEASE + + + org.springframework.integration + spring-integration-mail + 4.3.4.RELEASE + + + org.springframework.integration + spring-integration-ftp + 4.3.4.RELEASE + + + org.springframework.social + spring-social-core + 1.1.4.RELEASE + + + org.springframework.integration + spring-integration-file + 4.3.4.RELEASE + + + junit + junit + 4.12 + + + diff --git a/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java b/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java new file mode 100644 index 0000000000..4b6ee5d03a --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java @@ -0,0 +1,7 @@ +package com.baeldung.samples.endpoints; + +public interface Activator { + + public void handleMessage(T input); + +} diff --git a/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java b/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java new file mode 100644 index 0000000000..9b7c2763fc --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.samples.endpoints; + +import java.io.File; +import java.util.logging.Logger; + +import org.springframework.integration.IntegrationMessageHeaderAccessor; +import org.springframework.messaging.Message; + +public class ActivatorImpl implements Activator> { + + @Override + public void handleMessage(Message input) { + File filePayload = input.getPayload(); + IntegrationMessageHeaderAccessor accessor = new IntegrationMessageHeaderAccessor(input); + Logger.getAnonymousLogger().info("The file size "+filePayload.length()); + Logger.getAnonymousLogger().info("The time of the message "+accessor.getTimestamp()); + + } + +} diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup new file mode 100644 index 0000000000..5687a15f02 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml new file mode 100644 index 0000000000..b814e1a6a8 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml new file mode 100644 index 0000000000..567a3464e7 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml new file mode 100644 index 0000000000..3bbd59093a --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/source/penguins.jpg b/spring-integration/src/main/resources/source/penguins.jpg new file mode 100644 index 0000000000..030ab8a685 Binary files /dev/null and b/spring-integration/src/main/resources/source/penguins.jpg differ diff --git a/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java new file mode 100644 index 0000000000..96e5a98f41 --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.baeldung.samples; + +import org.apache.log4j.Logger; +import org.junit.Test; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.Scanner; + + +/** + * Starts the Spring Context and will initialize the Spring Integration routes. + * + * @author Baeldung + * @since 1.0 + * + */ +public final class FileCopyTest { + + private static final Logger LOGGER = Logger.getLogger(FileCopyTest.class); + + @Test + public void test() throws InterruptedException { + + + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-copy-context.xml"); + + Thread.sleep(5000); + + + } + + @Test + public void publish() throws InterruptedException { + + + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-publish-context.xml"); + + Thread.sleep(15000); + + + } +} 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..2777aa450c --- /dev/null +++ b/spring-jooq/README.md @@ -0,0 +1,7 @@ +### 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) + +In order to fix the error "Plugin execution not covered by lifecycle configuration: org.jooq:jooq-codegen-maven:3.7.3:generate (execution: default, phase: generate-sources)", right-click on the error message and choose "Mark goal generated as ignore in pom.xml". Until version 1.4.x, the maven-plugin-plugin was covered by the default lifecycle mapping that ships with m2e. + +Since version 1.5.x, the m2e default lifecycle mapping no longer covers the maven-plugin-plugin. diff --git a/jooq-spring/pom.xml b/spring-jooq/pom.xml similarity index 63% rename from jooq-spring/pom.xml rename to spring-jooq/pom.xml index e77ff0cbfd..bf60acd6f6 100644 --- a/jooq-spring/pom.xml +++ b/spring-jooq/pom.xml @@ -161,9 +161,88 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jooq + + jooq-codegen-maven + + + [3.7.3,) + + + generate + + + + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 3.7.3 1.4.191 @@ -173,6 +252,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 4568c0bc7f..30b39e1a4e 100644 --- a/spring-jpa/README.md +++ b/spring-jpa/README.md @@ -12,3 +12,13 @@ - [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) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/spring-jpa/src/main/resources/jpaConfig.xml b/spring-jpa/src/main/resources/persistence.xml similarity index 100% rename from spring-jpa/src/main/resources/jpaConfig.xml rename to spring-jpa/src/main/resources/persistence.xml diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 8248343105..011de70ad2 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -208,28 +208,44 @@ - - 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 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/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/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/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java index 7a23908fe5..406975b6cc 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java @@ -5,6 +5,7 @@ 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; @@ -39,9 +40,10 @@ public class HtmlUnitAndSpringIntegrationTest { // @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!"; - HtmlPage page = webClient.getPage("http://localhost/message/showForm"); + final HtmlPage page = webClient.getPage("http://localhost/message/showForm"); System.out.println(page.asXml()); final HtmlTextInput messageText = page.getHtmlElementById("message"); 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/EmployeeTestWithoutMockMvc.java new file mode 100644 index 0000000000..19806e0559 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeTestWithoutMockMvc.java @@ -0,0 +1,51 @@ +package com.baeldung.web.controller; + +import org.junit.Before; +import org.junit.Assert; +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 com.baeldung.model.Employee; +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class EmployeeTestWithoutMockMvc { + + @Autowired + private EmployeeController employeeController; + + @Before + public void setup() { + 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); + + Assert.assertTrue(employee1.getId() == 1L); + Assert.assertTrue(employee1.getName().equals("John")); + Assert.assertTrue(employee1.getContactNumber().equals("223334411")); + Assert.assertTrue(employee1.getWorkingArea().equals("rh")); + + Assert.assertTrue(employee2.getId() == 2L); + Assert.assertTrue(employee2.getName().equals("Peter")); + Assert.assertTrue(employee2.getContactNumber().equals("22001543")); + Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); + + Assert.assertTrue(employee3.getId() == 3L); + Assert.assertTrue(employee3.getName().equals("Mike")); + Assert.assertTrue(employee3.getContactNumber().equals("223334411")); + Assert.assertTrue(employee3.getWorkingArea().equals("admin")); + } + +} diff --git a/spring-mvc-no-xml/src/main/resources/webSecurityConfig.xml b/spring-mvc-no-xml/src/main/resources/webSecurityConfig.xml index 88af78dabc..b9e15c7bae 100644 --- a/spring-mvc-no-xml/src/main/resources/webSecurityConfig.xml +++ b/spring-mvc-no-xml/src/main/resources/webSecurityConfig.xml @@ -5,7 +5,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" > - + + diff --git a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml index 9bebc263be..5c7a0b52d4 100644 --- a/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-web-vs-initializer/src/main/webapp/WEB-INF/web.xml @@ -9,11 +9,11 @@ org.springframework.web.servlet.DispatcherServlet - 1 contextConfigLocation classpath*:mvc-configuration.xml + 1 diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java new file mode 100644 index 0000000000..96556bd5b1 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ErrorController.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class ErrorController { + + @RequestMapping(value = "500Error", method = RequestMethod.GET) + public void throwRuntimeException() { + throw new NullPointerException("Throwing a null pointer exception"); + } + + @RequestMapping(value = "errors", method = RequestMethod.GET) + public ModelAndView renderErrorPage(HttpServletRequest httpRequest) { + ModelAndView errorPage = new ModelAndView("errorPage"); + String errorMsg = ""; + int httpErrorCode = getErrorCode(httpRequest); + + switch (httpErrorCode) { + case 400: { + errorMsg = "Http Error Code : 400 . Bad Request"; + break; + } + case 401: { + errorMsg = "Http Error Code : 401. Unauthorized"; + break; + } + case 404: { + errorMsg = "Http Error Code : 404. Resource not found"; + break; + } + // Handle other 4xx error codes. + case 500: { + errorMsg = "Http Error Code : 500. Internal Server Error"; + break; + } + // Handle other 5xx error codes. + } + errorPage.addObject("errorMsg", errorMsg); + return errorPage; + } + + private int getErrorCode(HttpServletRequest httpRequest) { + return (Integer) httpRequest + .getAttribute("javax.servlet.error.status_code"); + } +} diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 29608a17ef..2240ac0a22 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -43,4 +43,7 @@ index.jsp + + /errors + \ No newline at end of file diff --git a/spring-rest-docs/pom.xml b/spring-rest-docs/pom.xml index 04ee11d0de..8e758eeb4a 100644 --- a/spring-rest-docs/pom.xml +++ b/spring-rest-docs/pom.xml @@ -63,7 +63,7 @@ maven-surefire-plugin - **/*Documentation.java + **/*IntegrationTest.java diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java similarity index 99% rename from spring-rest-docs/src/test/java/com/example/ApiDocumentation.java rename to spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index 5b753aff0c..0912023fb7 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -38,7 +38,7 @@ import static org.springframework.util.StringUtils.collectionToDelimitedString; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) @WebAppConfiguration -public class ApiDocumentation { +public class ApiDocumentationIntegrationTest { @Rule public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java similarity index 99% rename from spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java rename to spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index 7aea9d303c..1af626d03b 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -33,7 +33,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) @WebAppConfiguration -public class GettingStartedDocumentation { +public class GettingStartedDocumentationIntegrationTest { @Rule public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 69ab4ed361..6580f5ecc7 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -332,5 +332,17 @@ 3.4.1
- + + + + org.codehaus.mojo + findbugs-maven-plugin + 3.0.4 + + Max + FindDeadLocalStores,FindNullDeref + + + + diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/CustomFilter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/CustomFilter.java new file mode 100644 index 0000000000..8d2b919cb0 --- /dev/null +++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/CustomFilter.java @@ -0,0 +1,18 @@ +package org.baeldung.security.filter; + +import org.springframework.web.filter.GenericFilterBean; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; + +public class CustomFilter extends GenericFilterBean { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + chain.doFilter(request, response); + } + +} diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java new file mode 100644 index 0000000000..468c99cb2a --- /dev/null +++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java @@ -0,0 +1,17 @@ +package org.baeldung.security.filter.configuration; + +import org.baeldung.security.filter.CustomFilter; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + } + +} diff --git a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml index 48302e8e93..f840d3014e 100644 --- a/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml +++ b/spring-security-basic-auth/src/main/resources/webSecurityConfig.xml @@ -12,6 +12,7 @@ + @@ -22,4 +23,6 @@ + + \ No newline at end of file diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 760cf41c63..0812a73090 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -3,3 +3,4 @@ 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) +- [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) \ No newline at end of file diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6098fe5b65..288cc3d6ba 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE @@ -128,6 +128,7 @@ spring-security-taglibs 4.1.3.RELEASE + javax.servlet.jsp.jstl jstl-api @@ -239,6 +240,9 @@ + org.baeldung.Application + + UTF-8 1.8 2.4.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 b4e8d04b49..2d59fab6be 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 @@ -1,12 +1,17 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; -@SpringBootApplication +@Configuration +@EnableAutoConfiguration +@ComponentScan(excludeFilters = + @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*")) 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/voter/MinuteBasedVoter.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/MinuteBasedVoter.java new file mode 100644 index 0000000000..ca9072bcac --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/MinuteBasedVoter.java @@ -0,0 +1,33 @@ +package org.baeldung.voter; + +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; + +public class MinuteBasedVoter implements AccessDecisionVoter { + @Override + public boolean supports(ConfigAttribute attribute) { + return true; + } + + @Override + public boolean supports(Class clazz) { + return true; + } + + @Override + public int vote(Authentication authentication, Object object, Collection collection) { + return authentication + .getAuthorities() + .stream() + .map(GrantedAuthority::getAuthority) + .filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0) + .findAny() + .map(s -> ACCESS_DENIED) + .orElseGet(() -> ACCESS_ABSTAIN); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java new file mode 100644 index 0000000000..046eca9be7 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java @@ -0,0 +1,17 @@ +package org.baeldung.voter; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; + +@Configuration +@EnableAutoConfiguration +@ComponentScan(basePackages = {"org.baeldung.voter"}) +public class VoterApplication { + + public static void main(String[] args) { + SpringApplication.run(VoterApplication.class, args); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java new file mode 100644 index 0000000000..e282c794d0 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java @@ -0,0 +1,18 @@ +package org.baeldung.voter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Created by ambrusadrianz on 30/09/2016. + */ + +@Configuration +public class VoterMvcConfig extends WebMvcConfigurerAdapter { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("private"); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java new file mode 100644 index 0000000000..3330fda7ec --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java @@ -0,0 +1,69 @@ +package org.baeldung.voter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDecisionManager; +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.vote.AuthenticatedVoter; +import org.springframework.security.access.vote.RoleVoter; +import org.springframework.security.access.vote.UnanimousBased; +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.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.access.expression.WebExpressionVoter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import java.util.Arrays; +import java.util.List; + +//@Configuration +//@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + // @formatter: off + auth.inMemoryAuthentication() + .withUser("user").password("pass").roles("USER") + .and() + .withUser("admin").password("pass").roles("ADMIN"); + // @formatter: on + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter: off + http + // needed so our login could work + .csrf() + .disable() + .authorizeRequests() + .anyRequest() + .authenticated() + .accessDecisionManager(accessDecisionManager()) + .antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER") + .and() + .formLogin() + .permitAll() + .and() + .logout() + .permitAll() + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/login"); + // @formatter: on + } + + @Bean + public AccessDecisionManager accessDecisionManager() { + // @formatter: off + List> decisionVoters = + Arrays.asList( + new WebExpressionVoter(), + new RoleVoter(), + new AuthenticatedVoter(), + new MinuteBasedVoter()); + // @formatter: on + return new UnanimousBased(decisionVoters); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java new file mode 100644 index 0000000000..c206df7d1f --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java @@ -0,0 +1,15 @@ +package org.baeldung.voter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +/** + * Created by ambrusadrianz on 09/10/2016. + */ +@Configuration +@ImportResource({"classpath:spring-security.xml"}) +public class XmlSecurityConfig { + public XmlSecurityConfig() { + super(); + } +} diff --git a/spring-security-custom-permission/src/main/resources/spring-security.xml b/spring-security-custom-permission/src/main/resources/spring-security.xml new file mode 100644 index 0000000000..382dbf5dff --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/spring-security.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/resources/templates/private.html b/spring-security-custom-permission/src/main/resources/templates/private.html new file mode 100644 index 0000000000..5af8c7a13e --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/templates/private.html @@ -0,0 +1,10 @@ + + + + Private + + +

Congrats!

+ + \ No newline at end of file diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index b001a86955..145321b2f4 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 071fa14b71..296703c27e 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 5cd0ed51f3..957a349d3c 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java b/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java new file mode 100644 index 0000000000..445a70f29c --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java @@ -0,0 +1,17 @@ +package org.baeldung.example.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@EnableScheduling +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class AnotherBootApp extends WebMvcConfigurerAdapter { + + public static void main(final String[] args) { + SpringApplication.run(AnotherBootApp.class, args); + } +} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java index 64c84678af..89cec89951 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java @@ -1,6 +1,5 @@ package org.baeldung.persistence.dao.rsql; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.AndNode; @@ -8,26 +7,26 @@ import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.OrNode; import cz.jirutka.rsql.parser.ast.RSQLVisitor; -public class CustomRsqlVisitor implements RSQLVisitor, Void> { +public class CustomRsqlVisitor implements RSQLVisitor, Void> { - private UserRsqlSpecBuilder builder; + private GenericRsqlSpecBuilder builder; public CustomRsqlVisitor() { - builder = new UserRsqlSpecBuilder(); + builder = new GenericRsqlSpecBuilder(); } @Override - public Specification visit(final AndNode node, final Void param) { + public Specification visit(final AndNode node, final Void param) { return builder.createSpecification(node); } @Override - public Specification visit(final OrNode node, final Void param) { + public Specification visit(final OrNode node, final Void param) { return builder.createSpecification(node); } @Override - public Specification visit(final ComparisonNode node, final Void params) { + public Specification visit(final ComparisonNode node, final Void params) { return builder.createSpecification(node); } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java similarity index 65% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java rename to spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java index 202370a64b..01ec389465 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java @@ -3,7 +3,6 @@ package org.baeldung.persistence.dao.rsql; import java.util.ArrayList; import java.util.List; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specifications; import cz.jirutka.rsql.parser.ast.ComparisonNode; @@ -11,9 +10,9 @@ import cz.jirutka.rsql.parser.ast.LogicalNode; import cz.jirutka.rsql.parser.ast.LogicalOperator; import cz.jirutka.rsql.parser.ast.Node; -public class UserRsqlSpecBuilder { +public class GenericRsqlSpecBuilder { - public Specifications createSpecification(final Node node) { + public Specifications createSpecification(final Node node) { if (node instanceof LogicalNode) { return createSpecification((LogicalNode) node); } @@ -23,9 +22,9 @@ public class UserRsqlSpecBuilder { return null; } - public Specifications createSpecification(final LogicalNode logicalNode) { - final List> specs = new ArrayList>(); - Specifications temp; + public Specifications createSpecification(final LogicalNode logicalNode) { + final List> specs = new ArrayList>(); + Specifications temp; for (final Node node : logicalNode.getChildren()) { temp = createSpecification(node); if (temp != null) { @@ -33,7 +32,7 @@ public class UserRsqlSpecBuilder { } } - Specifications result = specs.get(0); + Specifications result = specs.get(0); if (logicalNode.getOperator() == LogicalOperator.AND) { for (int i = 1; i < specs.size(); i++) { @@ -50,8 +49,8 @@ public class UserRsqlSpecBuilder { return result; } - public Specifications createSpecification(final ComparisonNode comparisonNode) { - final Specifications result = Specifications.where(new UserRsqlSpecification(comparisonNode.getSelector(), comparisonNode.getOperator(), comparisonNode.getArguments())); + public Specifications createSpecification(final ComparisonNode comparisonNode) { + final Specifications result = Specifications.where(new GenericRsqlSpecification(comparisonNode.getSelector(), comparisonNode.getOperator(), comparisonNode.getArguments())); return result; } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java similarity index 87% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java rename to spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java index b7aaa14ba6..6609a87953 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java @@ -8,18 +8,17 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.ComparisonOperator; -public class UserRsqlSpecification implements Specification { +public class GenericRsqlSpecification implements Specification { private String property; private ComparisonOperator operator; private List arguments; - public UserRsqlSpecification(final String property, final ComparisonOperator operator, final List arguments) { + public GenericRsqlSpecification(final String property, final ComparisonOperator operator, final List arguments) { super(); this.property = property; this.operator = operator; @@ -27,7 +26,7 @@ public class UserRsqlSpecification implements Specification { } @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, final CriteriaBuilder builder) { + public Predicate toPredicate(final Root root, final CriteriaQuery query, final CriteriaBuilder builder) { final List args = castArguments(root); final Object argument = args.get(0); switch (RsqlSearchOperation.getSimpleOperator(operator)) { @@ -73,7 +72,7 @@ public class UserRsqlSpecification implements Specification { // === private - private List castArguments(final Root root) { + private List castArguments(final Root root) { final List args = new ArrayList(); final Class type = root.get(property).getJavaType(); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java index 0ce8c0300b..fda7b01c7a 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java @@ -1,9 +1,9 @@ package org.baeldung.persistence; -import org.baeldung.persistence.query.JPACriteriaQueryTest; -import org.baeldung.persistence.query.JPAQuerydslTest; -import org.baeldung.persistence.query.JPASpecificationTest; -import org.baeldung.persistence.query.RsqlTest; +import org.baeldung.persistence.query.JPACriteriaQueryIntegrationTest; +import org.baeldung.persistence.query.JPAQuerydslIntegrationTest; +import org.baeldung.persistence.query.JPASpecificationIntegrationTest; +import org.baeldung.persistence.query.RsqlIntegrationTest; import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -11,11 +11,11 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - RsqlTest.class - ,JPASpecificationTest.class + RsqlIntegrationTest.class + ,JPASpecificationIntegrationTest.class ,FooServicePersistenceIntegrationTest.class - ,JPAQuerydslTest.class - ,JPACriteriaQueryTest.class + ,JPAQuerydslIntegrationTest.class + ,JPACriteriaQueryIntegrationTest.class }) // public class PersistenceTestSuite { 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/JPACriteriaQueryIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java index 1d0826e6ba..e8e98074c6 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/JPACriteriaQueryIntegrationTest.java @@ -24,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPACriteriaQueryTest { +public class JPACriteriaQueryIntegrationTest { @Autowired private IUserDAO userApi; 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/JPAQuerydslIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java index d5fbc819fd..d397c3aac4 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/JPAQuerydslIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPAQuerydslTest { +public class JPAQuerydslIntegrationTest { @Autowired private MyUserRepository repo; 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/JPASpecificationIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java index 0d8773dd61..8bd4857e85 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/JPASpecificationIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPASpecificationTest { +public class JPASpecificationIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java index e0deb8d4ec..16dfa8a12f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java @@ -27,7 +27,7 @@ import cz.jirutka.rsql.parser.ast.Node; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class RsqlTest { +public class RsqlIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 930ab20262..99b391eda1 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.web.context.WebApplicationContext; @WebAppConfiguration @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) -public class LoggerInterceptorTest { +public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; 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/SessionTimerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 916a849c63..662fc997f9 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/SessionTimerInterceptorIntegrationTest.java @@ -28,7 +28,7 @@ import org.springframework.web.context.WebApplicationContext; @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class SessionTimerInterceptorTest { +public class SessionTimerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; 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/UserInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index ff40c86906..0e8f7c98ed 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/UserInterceptorIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class UserInterceptorTest { +public class UserInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index a8ca755044..98fb4b043b 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -2,15 +2,16 @@ ## Spring Thymeleaf Example Project - ### 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 mvn clean install + ### Run the Project mvn cargo:run - **note**: starts on port '8082' diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index d2b3be1651..e59ce77e57 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -166,47 +166,86 @@ ${maven-surefire-plugin.version} - **/*IntegrationTest.java - **/*LiveTest.java + **/*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 - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/mutation-testing/README.md b/testing/README.md similarity index 71% rename from mutation-testing/README.md rename to testing/README.md index f49aeeb881..121472ae13 100644 --- a/mutation-testing/README.md +++ b/testing/README.md @@ -5,4 +5,4 @@ ### 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/mutation-testing/pom.xml b/testing/pom.xml similarity index 97% rename from mutation-testing/pom.xml rename to testing/pom.xml index cdee59fcb4..aa523d95ef 100644 --- a/mutation-testing/pom.xml +++ b/testing/pom.xml @@ -1,77 +1,77 @@ - - 4.0.0 - com.baeldung - mutation-testing - 0.1-SNAPSHOT - mutation-testing - - - org.pitest - pitest-parent - 1.1.10 - pom - - - junit - junit - 4.9 - - - - - - org.pitest - pitest-maven - 1.1.10 - - - com.baeldung.testing.mutation.* - - - com.baeldung.mutation.test.* - - - - - org.jacoco - jacoco-maven-plugin - 0.7.7.201606060606 - - - - prepare-agent - - - - report - prepare-package - - report - - - - jacoco-check - - check - - - - - PACKAGE - - - LINE - COVEREDRATIO - 0.50 - - - - - - - - - - - + + 4.0.0 + com.baeldung + mutation-testing + 0.1-SNAPSHOT + mutation-testing + + + org.pitest + pitest-parent + 1.1.10 + pom + + + junit + junit + 4.9 + + + + + + org.pitest + pitest-maven + 1.1.10 + + + com.baeldung.testing.mutation.* + + + com.baeldung.mutation.test.* + + + + + org.jacoco + jacoco-maven-plugin + 0.7.7.201606060606 + + + + prepare-agent + + + + report + prepare-package + + report + + + + jacoco-check + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + 0.50 + + + + + + + + + + + diff --git a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java similarity index 97% rename from mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java rename to testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java index 0b166f1557..e264a4c759 100644 --- a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java +++ b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java @@ -1,15 +1,15 @@ -package com.baeldung.testing.mutation; - -public class Palindrome { - - public boolean isPalindrome(String inputString) { - if (inputString.length() == 0) { - return true; - } else { - char firstChar = inputString.charAt(0); - char lastChar = inputString.charAt(inputString.length() - 1); - String mid = inputString.substring(1, inputString.length() - 1); - return (firstChar == lastChar) && isPalindrome(mid); - } - } -} +package com.baeldung.testing.mutation; + +public class Palindrome { + + public boolean isPalindrome(String inputString) { + if (inputString.length() == 0) { + return true; + } else { + char firstChar = inputString.charAt(0); + char lastChar = inputString.charAt(inputString.length() - 1); + String mid = inputString.substring(1, inputString.length() - 1); + return (firstChar == lastChar) && isPalindrome(mid); + } + } +} diff --git a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java similarity index 96% rename from mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java rename to testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java index 3add6290f6..11ed966b16 100644 --- a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java +++ b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java @@ -1,34 +1,34 @@ -package com.baeldung.mutation.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.baeldung.testing.mutation.Palindrome; - -public class TestPalindrome { - @Test - public void whenEmptyString_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenPalindrom_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenNotPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("box")); - } - - @Test - public void whenNearPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("neon")); - } -} +package com.baeldung.mutation.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.baeldung.testing.mutation.Palindrome; + +public class TestPalindrome { + @Test + public void whenEmptyString_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenPalindrom_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenNotPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("box")); + } + + @Test + public void whenNearPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("neon")); + } +} diff --git a/xmlunit2-tutorial/README.md b/xmlunit2/README.md similarity index 100% rename from xmlunit2-tutorial/README.md rename to xmlunit2/README.md 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