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