diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index 232a4f0089..0902bd690e 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -11,6 +11,7 @@ 3.1.6 + 2.19.1 @@ -26,7 +27,7 @@ 2.19.1 - **/StudentTest.java + **/*LiveTest.java @@ -44,4 +45,5 @@ ${cxf.version} + diff --git a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java similarity index 65% rename from apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java rename to apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java index e1e5b60ec3..60fc0a10e7 100644 --- a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java +++ b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java @@ -2,20 +2,16 @@ package com.baeldung.cxf.introduction; import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; - import java.util.Map; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPBinding; -import com.baeldung.cxf.introduction.Baeldung; -import com.baeldung.cxf.introduction.Student; -import com.baeldung.cxf.introduction.StudentImpl; +import org.junit.Before; +import org.junit.Test; -public class StudentTest { +public class StudentLiveTest { private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung"); private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort"); @@ -25,7 +21,7 @@ public class StudentTest { { service = Service.create(SERVICE_NAME); - String endpointAddress = "http://localhost:8080/baeldung"; + final String endpointAddress = "http://localhost:8080/baeldung"; service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); } @@ -37,28 +33,28 @@ public class StudentTest { @Test public void whenUsingHelloMethod_thenCorrect() { - String endpointResponse = baeldungProxy.hello("Baeldung"); - String localResponse = baeldungImpl.hello("Baeldung"); + final String endpointResponse = baeldungProxy.hello("Baeldung"); + final String localResponse = baeldungImpl.hello("Baeldung"); assertEquals(localResponse, endpointResponse); } @Test public void whenUsingHelloStudentMethod_thenCorrect() { - Student student = new StudentImpl("John Doe"); - String endpointResponse = baeldungProxy.helloStudent(student); - String localResponse = baeldungImpl.helloStudent(student); + final Student student = new StudentImpl("John Doe"); + final String endpointResponse = baeldungProxy.helloStudent(student); + final String localResponse = baeldungImpl.helloStudent(student); assertEquals(localResponse, endpointResponse); } @Test public void usingGetStudentsMethod_thenCorrect() { - Student student1 = new StudentImpl("Adam"); + final Student student1 = new StudentImpl("Adam"); baeldungProxy.helloStudent(student1); - Student student2 = new StudentImpl("Eve"); + final Student student2 = new StudentImpl("Eve"); baeldungProxy.helloStudent(student2); - - Map students = baeldungProxy.getStudents(); + + final Map students = baeldungProxy.getStudents(); assertEquals("Adam", students.get(1).getName()); assertEquals("Eve", students.get(2).getName()); } diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index 1f83ecf934..b3a81aef82 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -13,6 +13,7 @@ UTF-8 3.1.7 4.5.2 + 2.19.1 @@ -28,7 +29,7 @@ 2.19.1 - **/ServiceTest + **/*LiveTest.java diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java similarity index 98% rename from apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java rename to apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java index 9dd63cf3ac..a2fd6be435 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Baeldung.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java @@ -9,7 +9,7 @@ import java.util.Map; @Path("baeldung") @Produces("text/xml") -public class Baeldung { +public class CourseRepository { private Map courses = new HashMap<>(); { @@ -69,4 +69,4 @@ public class Baeldung { } return null; } -} \ 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 index bb35bab3f8..d3ed2eb70e 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -7,8 +7,8 @@ import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; public class RestfulServer { public static void main(String args[]) throws Exception { JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean(); - factoryBean.setResourceClasses(Baeldung.class); - factoryBean.setResourceProvider(new SingletonResourceProvider(new Baeldung())); + factoryBean.setResourceClasses(CourseRepository.class); + factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository())); factoryBean.setAddress("http://localhost:8080/"); Server server = factoryBean.create(); @@ -18,4 +18,4 @@ public class RestfulServer { server.destroy(); System.exit(0); } -} \ No newline at end of file +} diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java similarity index 64% rename from apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java rename to apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java index b8fc833194..29c34ae16b 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceTest.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java @@ -1,5 +1,14 @@ 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; @@ -11,119 +20,111 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import javax.xml.bind.JAXB; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - -public class ServiceTest { +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 { - HttpPut httpPut = new HttpPut(BASE_URL + "3"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml"); + 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"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(404, response.getStatusLine().getStatusCode()); } - + @Test public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "1"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml"); + 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"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(304, response.getStatusLine().getStatusCode()); } - + @Test public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException { - HttpPut httpPut = new HttpPut(BASE_URL + "2"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml"); + 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"); - - HttpResponse response = client.execute(httpPut); + + final HttpResponse response = client.execute(httpPut); assertEquals(200, response.getStatusLine().getStatusCode()); - - Course course = getCourse(2); + + final Course course = getCourse(2); assertEquals(2, course.getId()); assertEquals("Apache CXF Support for RESTful", course.getName()); } - + @Test public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException { - HttpPost httpPost = new HttpPost(BASE_URL + "1/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml"); + 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"); - - HttpResponse response = client.execute(httpPost); + + final HttpResponse response = client.execute(httpPost); assertEquals(409, response.getStatusLine().getStatusCode()); } @Test public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException { - HttpPost httpPost = new HttpPost(BASE_URL + "2/students"); - InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml"); + 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"); - - HttpResponse response = client.execute(httpPost); + + final HttpResponse response = client.execute(httpPost); assertEquals(200, response.getStatusLine().getStatusCode()); - - Student student = getStudent(2, 3); + + final Student student = getStudent(2, 3); assertEquals(3, student.getId()); assertEquals("Student C", student.getName()); } - + @Test public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3"); - HttpResponse response = client.execute(httpDelete); + 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 { - HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); - HttpResponse response = client.execute(httpDelete); + final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1"); + final HttpResponse response = client.execute(httpDelete); assertEquals(200, response.getStatusLine().getStatusCode()); - - Course course = getCourse(1); + + 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 { - URL url = new URL(BASE_URL + courseOrder); - InputStream input = url.openStream(); + 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 { - URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder); - InputStream input = url.openStream(); + 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/autovalue-tutorial/README.md b/autovalue/README.md similarity index 100% rename from autovalue-tutorial/README.md rename to autovalue/README.md diff --git a/autovalue-tutorial/pom.xml b/autovalue/pom.xml similarity index 100% rename from autovalue-tutorial/pom.xml rename to autovalue/pom.xml diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java rename to autovalue/src/main/java/com/baeldung/autovalue/Foo.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java similarity index 100% rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java rename to autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java diff --git a/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java similarity index 100% rename from autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java rename to autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java diff --git a/cdi/pom.xml b/cdi/pom.xml index b771857938..30dd167fa8 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -45,8 +45,60 @@ + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + 4.3.1.RELEASE + 2.19.1 \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java similarity index 95% rename from cdi/src/test/java/com/baeldung/test/TestInterceptor.java rename to cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java index 3529a796d2..cca8cb7495 100644 --- a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import com.baeldung.interceptor.AuditedInterceptor; import com.baeldung.service.SuperService; -public class TestInterceptor { +public class InterceptorIntegrationTest { Weld weld; WeldContainer container; diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java similarity index 94% rename from cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java rename to cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java index 1f3a8d83e3..f711b0c8ce 100644 --- a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java +++ b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java @@ -16,19 +16,23 @@ import com.baeldung.spring.service.SpringSuperService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class TestSpringInterceptor { +public class SpringInterceptorIntegrationTest { @Autowired SpringSuperService springSuperService; @Autowired private List accumulator; + // + @Test public void givenService_whenServiceAndAspectExecuted_thenOk() { String code = "123456"; String result = springSuperService.getInfoFromService(code); + Assert.assertThat(accumulator.size(), is(2)); Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService")); Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService")); } + } diff --git a/core-java-8/README.md b/core-java-8/README.md deleted file mode 100644 index c130e6bd41..0000000000 --- a/core-java-8/README.md +++ /dev/null @@ -1,24 +0,0 @@ -========= - -## Core Java 8 Cookbooks and Examples - -### Relevant Articles: -- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) -- [Java – Directory Size](http://www.baeldung.com/java-folder-size) -- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) -- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) -- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) -- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) -- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) -- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) -- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) -- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) -- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) -- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) -- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) -- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) -- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml deleted file mode 100644 index 22e3bab595..0000000000 --- a/core-java-8/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - 4.0.0 - - com.baeldung - 1.0.0-SNAPSHOT - core-java8 - - core-java8 - - - - - - - commons-io - commons-io - 2.5 - - - - com.google.guava - guava - ${guava.version} - - - - org.apache.commons - commons-collections4 - 4.0 - - - - commons-codec - commons-codec - 1.10 - - - - org.apache.commons - commons-lang3 - 3.3.2 - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - - junit - junit - ${junit.version} - test - - - - org.assertj - assertj-core - 3.5.1 - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - core-java-8 - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - - - - - UTF-8 - - - 1.7.13 - 1.0.13 - - - 5.1.3.Final - - - 19.0 - 3.4 - - - 1.3 - 4.12 - 1.10.19 - - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - - - - \ No newline at end of file diff --git a/core-java-8/src/main/java/.gitignore b/core-java-8/src/main/java/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-8/src/main/java/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java deleted file mode 100644 index 5bc2d9a9eb..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.enums; - -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.List; -import java.util.stream.Collectors; - -public class Pizza { - - private static EnumSet deliveredPizzaStatuses = - EnumSet.of(PizzaStatusEnum.DELIVERED); - - private PizzaStatusEnum status; - - public enum PizzaStatusEnum { - ORDERED(5) { - @Override - public boolean isOrdered() { - return true; - } - }, - READY(2) { - @Override - public boolean isReady() { - return true; - } - }, - DELIVERED(0) { - @Override - public boolean isDelivered() { - return true; - } - }; - - private int timeToDelivery; - - public boolean isOrdered() { - return false; - } - - public boolean isReady() { - return false; - } - - public boolean isDelivered() { - return false; - } - - public int getTimeToDelivery() { - return timeToDelivery; - } - - PizzaStatusEnum(int timeToDelivery) { - this.timeToDelivery = timeToDelivery; - } - } - - public PizzaStatusEnum getStatus() { - return status; - } - - public void setStatus(PizzaStatusEnum status) { - this.status = status; - } - - public boolean isDeliverable() { - return this.status.isReady(); - } - - public void printTimeToDeliver() { - System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); - } - - public static List getAllUndeliveredPizzas(List input) { - return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); - } - - public static EnumMap> groupPizzaByStatus(List pzList) { - return pzList.stream().collect( - Collectors.groupingBy(Pizza::getStatus, - () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); - } - - public void deliver() { - if (isDeliverable()) { - PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); - this.setStatus(PizzaStatusEnum.DELIVERED); - } - } - -} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java deleted file mode 100644 index ed65919387..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.enums; - -public enum PizzaDeliveryStrategy { - EXPRESS { - @Override - public void deliver(Pizza pz) { - System.out.println("Pizza will be delivered in express mode"); - } - }, - NORMAL { - @Override - public void deliver(Pizza pz) { - System.out.println("Pizza will be delivered in normal mode"); - } - }; - - public abstract void deliver(Pizza pz); -} diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java deleted file mode 100644 index 5ccff5e959..0000000000 --- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.enums; - - -public enum PizzaDeliverySystemConfiguration { - INSTANCE; - - PizzaDeliverySystemConfiguration() { - // Do the configuration initialization which - // involves overriding defaults like delivery strategy - } - - private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL; - - public static PizzaDeliverySystemConfiguration getInstance() { - return INSTANCE; - } - - public PizzaDeliveryStrategy getDeliveryStrategy() { - return deliveryStrategy; - } - -} diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip deleted file mode 100644 index 03f840ae2b..0000000000 Binary files a/core-java-8/src/main/resources/compressed.zip and /dev/null differ diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml deleted file mode 100644 index eefdc7a337..0000000000 --- a/core-java-8/src/main/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - \ No newline at end of file diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt deleted file mode 100644 index c57eff55eb..0000000000 --- a/core-java-8/src/main/resources/unzipTest/test1.txt +++ /dev/null @@ -1 +0,0 @@ -Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt deleted file mode 100644 index c57eff55eb..0000000000 --- a/core-java-8/src/main/resources/zipTest/test1.txt +++ /dev/null @@ -1 +0,0 @@ -Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt deleted file mode 100644 index f0fb0f14d1..0000000000 --- a/core-java-8/src/main/resources/zipTest/test2.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is John \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt deleted file mode 100644 index 882edb168e..0000000000 --- a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is Tom \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt deleted file mode 100644 index a78c3fadc8..0000000000 --- a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt +++ /dev/null @@ -1 +0,0 @@ -My Name is Jane \ No newline at end of file diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt deleted file mode 100644 index 652d70630f..0000000000 --- a/core-java-8/src/test/resources/test.txt +++ /dev/null @@ -1 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/core-java/README.md b/core-java/README.md index 440af67252..48f0677461 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -18,3 +18,21 @@ - [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) +- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Random List Element](http://www.baeldung.com/java-random-list-element) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) +- [Java – Directory Size](http://www.baeldung.com/java-folder-size) +- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) +- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) +- [Java 8 New Features](http://www.baeldung.com/java-8-new-features) +- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) +- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) +- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index 75608b59ba..8b93e238eb 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -162,6 +162,8 @@ **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java @@ -277,6 +279,41 @@ + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/core-java-8/.gitignore b/core-java/src/main/java/com/baeldung/.gitignore similarity index 100% rename from core-java-8/.gitignore rename to core-java/src/main/java/com/baeldung/.gitignore diff --git a/core-java-8/src/main/java/com/baeldung/Adder.java b/core-java/src/main/java/com/baeldung/Adder.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Adder.java rename to core-java/src/main/java/com/baeldung/Adder.java diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java/src/main/java/com/baeldung/AdderImpl.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/AdderImpl.java rename to core-java/src/main/java/com/baeldung/AdderImpl.java diff --git a/core-java-8/src/main/java/com/baeldung/Bar.java b/core-java/src/main/java/com/baeldung/Bar.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Bar.java rename to core-java/src/main/java/com/baeldung/Bar.java diff --git a/core-java-8/src/main/java/com/baeldung/Baz.java b/core-java/src/main/java/com/baeldung/Baz.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Baz.java rename to core-java/src/main/java/com/baeldung/Baz.java diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java/src/main/java/com/baeldung/Foo.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/Foo.java rename to core-java/src/main/java/com/baeldung/Foo.java diff --git a/core-java-8/src/main/java/com/baeldung/FooExtended.java b/core-java/src/main/java/com/baeldung/FooExtended.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/FooExtended.java rename to core-java/src/main/java/com/baeldung/FooExtended.java diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java/src/main/java/com/baeldung/UseFoo.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/UseFoo.java rename to core-java/src/main/java/com/baeldung/UseFoo.java diff --git a/core-java-8/src/main/java/com/baeldung/datetime/README.md b/core-java/src/main/java/com/baeldung/datetime/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/datetime/README.md rename to core-java/src/main/java/com/baeldung/datetime/README.md diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 74% rename from core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java/src/main/java/com/baeldung/datetime/UseDuration.java index 125b6fbe38..31b45aab84 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java @@ -5,12 +5,12 @@ import java.time.LocalTime; import java.time.Period; public class UseDuration { - - public LocalTime modifyDates(LocalTime localTime,Duration duration){ + + public LocalTime modifyDates(LocalTime localTime, Duration duration) { return localTime.plus(duration); } - - public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){ + + public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) { return Duration.between(localTime1, localTime2); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 67% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java index 47b1b3f67d..82f5745b3c 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; public class UseLocalDate { - - public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){ + + public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { return LocalDate.of(year, month, dayOfMonth); } - - public LocalDate getLocalDateUsingParseMethod(String representation){ + + public LocalDate getLocalDateUsingParseMethod(String representation) { return LocalDate.parse(representation); } - - public LocalDate getLocalDateFromClock(){ + + public LocalDate getLocalDateFromClock() { LocalDate localDate = LocalDate.now(); return localDate; } - - public LocalDate getNextDay(LocalDate localDate){ + + public LocalDate getNextDay(LocalDate localDate) { return localDate.plusDays(1); } - - public LocalDate getPreviousDay(LocalDate localDate){ + + public LocalDate getPreviousDay(LocalDate localDate) { return localDate.minus(1, ChronoUnit.DAYS); } - - public DayOfWeek getDayOfWeek(LocalDate localDate){ + + public DayOfWeek getDayOfWeek(LocalDate localDate) { DayOfWeek day = localDate.getDayOfWeek(); return day; } - - public LocalDate getFirstDayOfMonth(){ + + public LocalDate getFirstDayOfMonth() { LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } - - public LocalDateTime getStartOfDay(LocalDate localDate){ + + public LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 87% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java index 7aa1eaa276..7f39ac2f91 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -3,8 +3,8 @@ package com.baeldung.datetime; import java.time.LocalDateTime; public class UseLocalDateTime { - - public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){ + + public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { return LocalDateTime.parse(representation); } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 67% rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java index e13fd10d6f..9bd8f9706c 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java @@ -4,32 +4,32 @@ import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class UseLocalTime { - - public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){ + + public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { LocalTime localTime = LocalTime.of(hour, min, seconds); return localTime; } - - public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){ + + public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { LocalTime localTime = LocalTime.parse(timeRepresentation); return localTime; } - - public LocalTime getLocalTimeFromClock(){ + + public LocalTime getLocalTimeFromClock() { LocalTime localTime = LocalTime.now(); return localTime; } - - public LocalTime addAnHour(LocalTime localTime){ - LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS); + + public LocalTime addAnHour(LocalTime localTime) { + LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS); return newTime; } - - public int getHourFromLocalTime(LocalTime localTime){ + + public int getHourFromLocalTime(LocalTime localTime) { return localTime.getHour(); } - - public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){ + + public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { return localTime.withMinute(minute); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 73% rename from core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java/src/main/java/com/baeldung/datetime/UsePeriod.java index 326cfad650..5a42ef83b4 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java +++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java @@ -4,12 +4,12 @@ import java.time.LocalDate; import java.time.Period; public class UsePeriod { - - public LocalDate modifyDates(LocalDate localDate,Period period){ + + public LocalDate modifyDates(LocalDate localDate, Period period) { return localDate.plus(period); } - - public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){ + + public Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { return Period.between(localDate1, localDate2); } } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 87% rename from core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java/src/main/java/com/baeldung/datetime/UseToInstant.java index 1ddb096cf6..94154ce5c0 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java @@ -6,13 +6,13 @@ import java.util.Calendar; import java.util.Date; public class UseToInstant { - - public LocalDateTime convertDateToLocalDate(Date date){ + + public LocalDateTime convertDateToLocalDate(Date date) { LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return localDateTime; } - - public LocalDateTime convertDateToLocalDate(Calendar calendar){ + + public LocalDateTime convertDateToLocalDate(Calendar calendar) { LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); return localDateTime; } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 90% rename from core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index 0369de9835..2d1b17484b 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -5,8 +5,8 @@ import java.time.ZoneId; import java.time.ZonedDateTime; public class UseZonedDateTime { - - public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){ + + public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); return zonedDateTime; } diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java rename to core-java/src/main/java/com/baeldung/doublecolon/Computer.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java rename to core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java rename to core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java b/core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java rename to core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java b/core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java rename to core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java index 7742781081..bad134bf00 100644 --- a/core-java/src/main/java/com/baeldung/enums/Pizza.java +++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java @@ -1,11 +1,5 @@ package com.baeldung.enums; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.collections15.Predicate; - -import java.io.IOException; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; @@ -13,13 +7,11 @@ import java.util.stream.Collectors; public class Pizza { - private static EnumSet undeliveredPizzaStatuses = - EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY); + private static EnumSet deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED); - private PizzaStatus status; + private PizzaStatusEnum status; - @JsonFormat(shape = JsonFormat.Shape.OBJECT) - public enum PizzaStatus { + public enum PizzaStatusEnum { ORDERED(5) { @Override public boolean isOrdered() { @@ -53,21 +45,20 @@ public class Pizza { return false; } - @JsonProperty("timeToDelivery") public int getTimeToDelivery() { return timeToDelivery; } - PizzaStatus(int timeToDelivery) { + PizzaStatusEnum(int timeToDelivery) { this.timeToDelivery = timeToDelivery; } } - public PizzaStatus getStatus() { + public PizzaStatusEnum getStatus() { return status; } - public void setStatus(PizzaStatus status) { + public void setStatus(PizzaStatusEnum status) { this.status = status; } @@ -80,31 +71,18 @@ public class Pizza { } public static List getAllUndeliveredPizzas(List input) { - return input.stream().filter( - (s) -> undeliveredPizzaStatuses.contains(s.getStatus())) - .collect(Collectors.toList()); + return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); } - public static EnumMap> - groupPizzaByStatus(List pzList) { - return pzList.stream().collect( - Collectors.groupingBy(Pizza::getStatus, - () -> new EnumMap<>(PizzaStatus.class), Collectors.toList())); + public static EnumMap> groupPizzaByStatus(List pzList) { + return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); } public void deliver() { if (isDeliverable()) { PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); - this.setStatus(PizzaStatus.DELIVERED); + this.setStatus(PizzaStatusEnum.DELIVERED); } } - public static String getJsonString(Pizza pz) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz); - } - - private static Predicate thatAreNotDelivered() { - return entry -> undeliveredPizzaStatuses.contains(entry.getStatus()); - } } \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/README.md b/core-java/src/main/java/com/baeldung/enums/README.md similarity index 100% rename from core-java-8/src/main/java/com/baeldung/enums/README.md rename to core-java/src/main/java/com/baeldung/enums/README.md diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java similarity index 94% rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index f1ab2d8d09..ae79787570 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction { private Collection createSubtasks() { - List subtasks = - new ArrayList<>(); + List subtasks = new ArrayList<>(); String partOne = workLoad.substring(0, workLoad.length() / 2); String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length()); diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java similarity index 60% rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java index 5d4d97b805..af9805c33f 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask { if (arr.length > THRESHOLD) { - return ForkJoinTask.invokeAll(createSubtasks()) - .stream() - .mapToInt(ForkJoinTask::join) - .sum(); + return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum(); } else { return processing(arr); @@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask { private Collection createSubtasks() { List dividedTasks = new ArrayList<>(); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, 0, arr.length / 2))); - dividedTasks.add(new CustomRecursiveTask( - Arrays.copyOfRange(arr, arr.length / 2, arr.length))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, 0, arr.length / 2))); + dividedTasks.add(new CustomRecursiveTask(Arrays.copyOfRange(arr, arr.length / 2, arr.length))); return dividedTasks; } private Integer processing(int[] arr) { - return Arrays.stream(arr) - .filter(a -> a > 10 && a < 27) - .map(a -> a * 10) - .sum(); + return Arrays.stream(arr).filter(a -> a > 10 && a < 27).map(a -> a * 10).sum(); } } diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java similarity index 99% rename from core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java rename to core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java index 521616600f..fd24a6fc66 100644 --- a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java @@ -1,6 +1,5 @@ package com.baeldung.forkjoin.util; - import java.util.concurrent.ForkJoinPool; public class PoolUtil { diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java new file mode 100644 index 0000000000..0d66406ac2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java @@ -0,0 +1,56 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; +import java.util.List; + +public class PersistentCookieStore implements CookieStore, Runnable { + CookieStore store; + + public PersistentCookieStore() { + store = new CookieManager().getCookieStore(); + // deserialize cookies into store + Runtime.getRuntime().addShutdownHook(new Thread(this)); + } + + @Override + public void run() { + // serialize cookies to persistent storage + } + + @Override + public void add(URI uri, HttpCookie cookie) { + store.add(uri, cookie); + + } + + @Override + public List get(URI uri) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getCookies() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getURIs() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean remove(URI uri, HttpCookie cookie) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean removeAll() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java new file mode 100644 index 0000000000..6d6371bfe0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java @@ -0,0 +1,26 @@ +package com.baeldung.java.networking.cookies; + +import java.net.*; + +public class ProxyAcceptCookiePolicy implements CookiePolicy { + String acceptedProxy; + + public ProxyAcceptCookiePolicy(String acceptedProxy) { + this.acceptedProxy = acceptedProxy; + } + + public boolean shouldAccept(URI uri, HttpCookie cookie) { + String host; + try { + host = InetAddress.getByName(uri.getHost()).getCanonicalHostName(); + } catch (UnknownHostException e) { + host = uri.getHost(); + } + + if (!HttpCookie.domainMatches(acceptedProxy, host)) { + return false; + } + + return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java new file mode 100644 index 0000000000..1fb9af3a9d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoClient { + private DatagramSocket socket; + private InetAddress address; + + private byte[] buf; + + public EchoClient() { + try { + socket = new DatagramSocket(); + address = InetAddress.getByName("localhost"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public String sendEcho(String msg) { + DatagramPacket packet = null; + try { + buf=msg.getBytes(); + packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } catch (IOException e) { + e.printStackTrace(); + } + String received = new String(packet.getData(), 0, packet.getLength()); + return received; + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java new file mode 100644 index 0000000000..900d330786 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java @@ -0,0 +1,42 @@ +package com.baeldung.java.networking.udp; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class EchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public EchoServer() throws IOException { + socket = new DatagramSocket(4445); + } + + public void run() { + running = true; + + while (running) { + try { + + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java index 285d4e51fc..1d4e01bbc3 100644 --- a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java @@ -1,21 +1,21 @@ 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.nio.channels.Selector; +import java.nio.channels.SelectionKey; +import java.nio.ByteBuffer; +import java.io.IOException; import java.util.Set; +import java.util.Iterator; +import java.net.InetSocketAddress; +import java.io.File; public class EchoServer { public static void main(String[] args) - throws IOException { + throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); @@ -49,6 +49,7 @@ public class EchoServer { } } + public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; @@ -59,4 +60,4 @@ public class EchoServer { return builder.start(); } -} \ No newline at end of file +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java/src/main/java/com/baeldung/java_8_features/Address.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Address.java rename to core-java/src/main/java/com/baeldung/java_8_features/Address.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java/src/main/java/com/baeldung/java_8_features/CustomException.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java rename to core-java/src/main/java/com/baeldung/java_8_features/CustomException.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java/src/main/java/com/baeldung/java_8_features/Detail.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java rename to core-java/src/main/java/com/baeldung/java_8_features/Detail.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java/src/main/java/com/baeldung/java_8_features/User.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/User.java rename to core-java/src/main/java/com/baeldung/java_8_features/User.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java similarity index 89% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java rename to core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java index 011173bcaf..045fc90590 100644 --- a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java @@ -9,7 +9,7 @@ public interface Vehicle { } default long[] startPosition() { - return new long[]{23, 15}; + return new long[] { 23, 15 }; } default String getOverview() { diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java similarity index 63% rename from core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java rename to core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java index 83e55f5f4d..64bec0246d 100644 --- a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java +++ b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java @@ -1,9 +1,9 @@ package com.baeldung.java_8_features; -public class VehicleImpl implements Vehicle { +public class VehicleImpl implements Vehicle { @Override public void moveTo(long altitude, long longitude) { - //do nothing + // do nothing } } diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 27fd84e374..7f87b47476 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -14,7 +14,6 @@ public class Screenshot { } 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); diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java new file mode 100644 index 0000000000..570bd60b2d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -0,0 +1,41 @@ +package com.baeldung.socket; + +import java.io.*; +import java.net.*; + +public class EchoClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { + System.out.print(e); + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java new file mode 100644 index 0000000000..b920967545 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java @@ -0,0 +1,70 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoMultiServer { + private ServerSocket serverSocket; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + while (true) + new EchoClientHandler(serverSocket.accept()).run(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + stop(); + } + + } + + public void stop() { + try { + + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private static class EchoClientHandler extends Thread { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public EchoClientHandler(Socket socket) { + this.clientSocket = socket; + } + + public void run() { + try { + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("bye"); + break; + } + out.println(inputLine); + } + + in.close(); + out.close(); + clientSocket.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] args) { + EchoMultiServer server = new EchoMultiServer(); + server.start(5555); + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java new file mode 100644 index 0000000000..dfd281d51c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java @@ -0,0 +1,49 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class EchoServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (".".equals(inputLine)) { + out.println("good bye"); + break; + } + out.println(inputLine); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + EchoServer server = new EchoServer(); + server.start(4444); + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java new file mode 100644 index 0000000000..e6f14bb2b6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java @@ -0,0 +1,44 @@ +package com.baeldung.socket; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +public class GreetClient { + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void startConnection(String ip, int port) { + try { + clientSocket = new Socket(ip, port); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } catch (IOException e) { + + } + + } + + public String sendMessage(String msg) { + try { + out.println(msg); + return in.readLine(); + } catch (Exception e) { + return null; + } + } + + public void stopConnection() { + try { + in.close(); + out.close(); + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java new file mode 100644 index 0000000000..05bc65a65e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/socket/GreetServer.java @@ -0,0 +1,46 @@ +package com.baeldung.socket; + +import java.net.*; +import java.io.*; + +public class GreetServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private PrintWriter out; + private BufferedReader in; + + public void start(int port) { + try { + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String greeting = in.readLine(); + if ("hello server".equals(greeting)) + out.println("hello client"); + else + out.println("unrecognised greeting"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void stop() { + try { + in.close(); + out.close(); + clientSocket.close(); + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void main(String[] args) { + GreetServer server = new GreetServer(); + server.start(6666); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java/src/main/java/com/baeldung/streamApi/Product.java similarity index 99% rename from core-java-8/src/main/java/com/baeldung/streamApi/Product.java rename to core-java/src/main/java/com/baeldung/streamApi/Product.java index 18f3a61904..26b8bd6fed 100644 --- a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java +++ b/core-java/src/main/java/com/baeldung/streamApi/Product.java @@ -44,7 +44,6 @@ public class Product { this.name = name; } - public static Stream streamOf(List list) { return (list == null || list.isEmpty()) ? Stream.empty() : list.stream(); } diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java similarity index 66% rename from core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java rename to core-java/src/main/java/com/baeldung/threadpool/CountingTask.java index 05aa14c5ae..effdf54916 100644 --- a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java +++ b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -14,9 +14,7 @@ public class CountingTask extends RecursiveTask { @Override protected Integer compute() { - return node.value + node.children.stream() - .map(childNode -> new CountingTask(childNode).fork()) - .collect(Collectors.summingInt(ForkJoinTask::join)); + return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join)); } } diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java rename to core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java rename to core-java/src/main/java/com/baeldung/threadpool/TreeNode.java diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java/src/main/java/com/baeldung/unzip/UnzipFile.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java rename to core-java/src/main/java/com/baeldung/unzip/UnzipFile.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java/src/main/java/com/baeldung/zip/ZipDirectory.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java rename to core-java/src/main/java/com/baeldung/zip/ZipDirectory.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java/src/main/java/com/baeldung/zip/ZipFile.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipFile.java rename to core-java/src/main/java/com/baeldung/zip/ZipFile.java diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java rename to core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.java diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java index d4a6a0f42e..6329f41252 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java @@ -1,7 +1,5 @@ package org.baeldung.equalshashcode.entities; -import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Set; @@ -10,7 +8,7 @@ public class ComplexClass { private List genericList; private Set integerSet; - public ComplexClass(ArrayList genericArrayList, HashSet integerHashSet) { + public ComplexClass(List genericArrayList, Set integerHashSet) { super(); this.genericList = genericArrayList; this.integerSet = integerHashSet; diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java index 2c52a17904..09344902b7 100644 --- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -4,8 +4,8 @@ import javax.swing.JOptionPane; public class ExecutableMavenJar { - public static void main(String[] args) { - JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); - } + public static void main(String[] args) { + JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); + } } diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java/src/main/resources/dirCompressed.zip similarity index 100% rename from core-java-8/src/main/resources/dirCompressed.zip rename to core-java/src/main/resources/dirCompressed.zip diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java/src/main/resources/fileTest.txt similarity index 100% rename from core-java-8/src/main/resources/fileTest.txt rename to core-java/src/main/resources/fileTest.txt diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java/src/main/resources/multiCompressed.zip similarity index 100% rename from core-java-8/src/main/resources/multiCompressed.zip rename to core-java/src/main/resources/multiCompressed.zip diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp new file mode 100644 index 0000000000..20f137b416 --- /dev/null +++ b/core-java/src/main/resources/targetFile.tmp @@ -0,0 +1,2 @@ +line 1 +a second line \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 87% rename from core-java-8/src/test/java/com/baeldung/CharToStringTest.java rename to core-java/src/test/java/com/baeldung/CharToStringUnitTest.java index d91016d104..78742e356d 100644 --- a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java +++ b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java @@ -4,10 +4,10 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -public class CharToStringTest { +public class CharToStringUnitTest { @Test - public void givenChar_whenCallingStringValueOf_shouldConvertToString(){ + public void givenChar_whenCallingStringValueOf_shouldConvertToString() { final char givenChar = 'x'; final String result = String.valueOf(givenChar); @@ -16,7 +16,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){ + public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() { final char givenChar = 'x'; final String result = Character.toString(givenChar); @@ -25,7 +25,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){ + public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3() { final char givenChar = 'x'; final String result = new Character(givenChar).toString(); @@ -34,7 +34,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenConcatenated_shouldConvertToString4(){ + public void givenChar_whenConcatenated_shouldConvertToString4() { final char givenChar = 'x'; final String result = givenChar + ""; @@ -43,7 +43,7 @@ public class CharToStringTest { } @Test - public void givenChar_whenFormated_shouldConvertToString5(){ + public void givenChar_whenFormated_shouldConvertToString5() { final char givenChar = 'x'; final String result = String.format("%c", givenChar); diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/RandomListElementTest.java rename to core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java index 1918c801dc..6ae7c40f4d 100644 --- a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java +++ b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.util.*; import java.util.concurrent.ThreadLocalRandom; -public class RandomListElementTest { +public class RandomListElementUnitTest { @Test public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { @@ -20,7 +20,7 @@ public class RandomListElementTest { public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { List givenList = Lists.newArrayList(1, 2, 3); - givenList.get((int)(Math.random() * givenList.size())); + givenList.get((int) (Math.random() * givenList.size())); } @Test diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java rename to core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java index 6c1493d89b..a7ad0bf114 100644 --- a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java +++ b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung; -import com.google.common.primitives.Ints; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; -public class StringToIntOrIntegerTest { +import org.junit.Test; + +import com.google.common.primitives.Ints; + +public class StringToIntOrIntegerUnitTest { @Test public void givenString_whenParsingInt_shouldConvertToInt() { @@ -16,7 +17,6 @@ public class StringToIntOrIntegerTest { assertThat(result).isEqualTo(42); } - @Test public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() { String givenString = "42"; diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java similarity index 54% rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java rename to core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java index d94f72b685..dbddbe6c54 100644 --- a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java +++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java @@ -36,198 +36,143 @@ import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class Java8CollectorsTest { +public class Java8CollectorsUnitTest { private final List givenList = Arrays.asList("a", "bb", "ccc", "dd"); @Test public void whenCollectingToList_shouldCollectToList() throws Exception { - final List result = givenList.stream() - .collect(toList()); + final List result = givenList.stream().collect(toList()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToList_shouldCollectToSet() throws Exception { - final Set result = givenList.stream() - .collect(toSet()); + final Set result = givenList.stream().collect(toSet()); - assertThat(result) - .containsAll(givenList); + assertThat(result).containsAll(givenList); } @Test public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { - final List result = givenList.stream() - .collect(toCollection(LinkedList::new)); + final List result = givenList.stream().collect(toCollection(LinkedList::new)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(LinkedList.class); + assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class); } @Test public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { assertThatThrownBy(() -> { - givenList.stream() - .collect(toCollection(ImmutableList::of)); + givenList.stream().collect(toCollection(ImmutableList::of)); }).isInstanceOf(UnsupportedOperationException.class); } @Test public void whenCollectingToMap_shouldCollectToMap() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { - final Map result = givenList.stream() - .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); + final Map result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); - assertThat(result) - .containsEntry("a", 1) - .containsEntry("bb", 2) - .containsEntry("ccc", 3) - .containsEntry("dd", 2); + assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); } @Test public void whenCollectingAndThen_shouldCollect() throws Exception { - final List result = givenList.stream() - .collect(collectingAndThen(toList(), ImmutableList::copyOf)); + final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf)); - assertThat(result) - .containsAll(givenList) - .isInstanceOf(ImmutableList.class); + assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class); } @Test public void whenJoining_shouldJoin() throws Exception { - final String result = givenList.stream() - .collect(joining()); + final String result = givenList.stream().collect(joining()); - assertThat(result) - .isEqualTo("abbcccdd"); + assertThat(result).isEqualTo("abbcccdd"); } @Test public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { - final String result = givenList.stream() - .collect(joining(" ")); + final String result = givenList.stream().collect(joining(" ")); - assertThat(result) - .isEqualTo("a bb ccc dd"); + assertThat(result).isEqualTo("a bb ccc dd"); } @Test public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { - final String result = givenList.stream() - .collect(joining(" ", "PRE-", "-POST")); + final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST")); - assertThat(result) - .isEqualTo("PRE-a bb ccc dd-POST"); + assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); } @Test public void whenPartitioningBy_shouldPartition() throws Exception { - final Map> result = givenList.stream() - .collect(partitioningBy(s -> s.length() > 2)); + final Map> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2)); - assertThat(result) - .containsKeys(true, false) - .satisfies(booleanListMap -> { - assertThat(booleanListMap.get(true)) - .contains("ccc"); + assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> { + assertThat(booleanListMap.get(true)).contains("ccc"); - assertThat(booleanListMap.get(false)) - .contains("a", "bb", "dd"); - }); + assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); + }); } @Test public void whenCounting_shouldCount() throws Exception { - final Long result = givenList.stream() - .collect(counting()); + final Long result = givenList.stream().collect(counting()); - assertThat(result) - .isEqualTo(4); + assertThat(result).isEqualTo(4); } @Test public void whenSummarizing_shouldSummarize() throws Exception { - final DoubleSummaryStatistics result = givenList.stream() - .collect(summarizingDouble(String::length)); + final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length)); - assertThat(result.getAverage()) - .isEqualTo(2); - assertThat(result.getCount()) - .isEqualTo(4); - assertThat(result.getMax()) - .isEqualTo(3); - assertThat(result.getMin()) - .isEqualTo(1); - assertThat(result.getSum()) - .isEqualTo(8); + assertThat(result.getAverage()).isEqualTo(2); + assertThat(result.getCount()).isEqualTo(4); + assertThat(result.getMax()).isEqualTo(3); + assertThat(result.getMin()).isEqualTo(1); + assertThat(result.getSum()).isEqualTo(8); } @Test public void whenAveraging_shouldAverage() throws Exception { - final Double result = givenList.stream() - .collect(averagingDouble(String::length)); + final Double result = givenList.stream().collect(averagingDouble(String::length)); - assertThat(result) - .isEqualTo(2); + assertThat(result).isEqualTo(2); } @Test public void whenSumming_shouldSum() throws Exception { - final Double result = givenList.stream() - .collect(summingDouble(String::length)); + final Double result = givenList.stream().collect(summingDouble(String::length)); - assertThat(result) - .isEqualTo(8); + assertThat(result).isEqualTo(8); } @Test public void whenMaxingBy_shouldMaxBy() throws Exception { - final Optional result = givenList.stream() - .collect(maxBy(Comparator.naturalOrder())); + final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder())); - assertThat(result) - .isPresent() - .hasValue("dd"); + assertThat(result).isPresent().hasValue("dd"); } @Test public void whenGroupingBy_shouldGroupBy() throws Exception { - final Map> result = givenList.stream() - .collect(groupingBy(String::length, toSet())); + final Map> result = givenList.stream().collect(groupingBy(String::length, toSet())); - assertThat(result) - .containsEntry(1, newHashSet("a")) - .containsEntry(2, newHashSet("bb", "dd")) - .containsEntry(3, newHashSet("ccc")); + assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc")); } - @Test public void whenCreatingCustomCollector_shouldCollect() throws Exception { - final ImmutableSet result = givenList.stream() - .collect(toImmutableSet()); + final ImmutableSet result = givenList.stream().collect(toImmutableSet()); - assertThat(result) - .isInstanceOf(ImmutableSet.class) - .contains("a", "bb", "ccc", "dd"); + assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd"); } diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java similarity index 88% rename from core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java rename to core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java index 5363a73afa..df12c3d79e 100644 --- a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java +++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java @@ -1,24 +1,26 @@ package com.baeldung.completablefuture; -import java.util.concurrent.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CompletableFutureTest { +public class CompletableFutureUnitTest { @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { - Future completableFuture = calculateAsync(); String result = completableFuture.get(); assertEquals("Hello", result); - } public Future calculateAsync() throws InterruptedException { @@ -35,15 +37,12 @@ public class CompletableFutureTest { @Test public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException { - Future completableFuture = CompletableFuture.completedFuture("Hello"); String result = completableFuture.get(); assertEquals("Hello", result); - } - public Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); @@ -56,90 +55,67 @@ public class CompletableFutureTest { return completableFuture; } - @Test(expected = CancellationException.class) public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException { - Future future = calculateAsyncWithCancellation(); future.get(); - } @Test public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException { - CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello"); assertEquals("Hello", future.get()); - } @Test public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); future.get(); - } @Test public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); future.get(); - } @Test public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApply(s -> s + " World"); assertEquals("Hello World", future.get()); - } @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") - .thenCombine(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); - } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - - CompletableFuture.supplyAsync(() -> "Hello") - .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), - (s1, s2) -> System.out.println(s1 + s2)); - + CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); } @Test public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException { - CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World"); @@ -154,17 +130,13 @@ public class CompletableFutureTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3) - .map(CompletableFuture::join) - .collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); - } @Test public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException { - String name = null; // ... @@ -177,12 +149,10 @@ public class CompletableFutureTest { }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); - } @Test(expected = ExecutionException.class) public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = new CompletableFuture<>(); // ... @@ -192,18 +162,15 @@ public class CompletableFutureTest { // ... completableFuture.get(); - } @Test public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World"); assertEquals("Hello World", future.get()); - } } \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java rename to core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java index 4bce40c2d9..e4753dbd5c 100644 --- a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java +++ b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java @@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit; import static org.assertj.core.api.Assertions.assertThat; -public class JavaUtilTimeTest { +public class JavaUtilTimeUnitTest { @Test public void currentTime() { diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java rename to core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index 69a289fd02..906d641632 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -7,7 +7,7 @@ import java.time.Month; import org.junit.Assert; import org.junit.Test; -public class UseLocalDateTimeTest { +public class UseLocalDateTimeUnitTest { UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java rename to core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index 8af33393be..dcfca792af 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -3,12 +3,11 @@ package com.baeldung.datetime; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.Month; import org.junit.Assert; import org.junit.Test; -public class UseLocalDateTest { +public class UseLocalDateUnitTest { UseLocalDate useLocalDate = new UseLocalDate(); diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java rename to core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java index 7776fad363..520b79d4bf 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java @@ -5,7 +5,7 @@ import java.time.LocalTime; import org.junit.Assert; import org.junit.Test; -public class UseLocalTimeTest { +public class UseLocalTimeUnitTest { UseLocalTime useLocalTime = new UseLocalTime(); diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 86% rename from core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java rename to core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java index 8a3228aaa5..a060d974ed 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java @@ -1,15 +1,12 @@ package com.baeldung.datetime; import java.time.LocalDate; -import java.time.LocalDateTime; import java.time.Period; -import java.time.ZoneId; -import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Test; -public class UsePeriodTest { +public class UsePeriodUnitTest { UsePeriod usingPeriod=new UsePeriod(); @Test diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java rename to core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java index 5af01ad678..d5652430fe 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -7,7 +7,7 @@ import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Test; -public class UseZonedDateTimeTest { +public class UseZonedDateTimeUnitTest { UseZonedDateTime zonedDateTime=new UseZonedDateTime(); diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java rename to core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java index 85194f5aa6..f69e4b03ee 100644 --- a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java +++ b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java @@ -13,7 +13,7 @@ import java.util.function.BiFunction; import static com.baeldung.doublecolon.ComputerUtils.*; -public class TestComputerUtils { +public class ComputerUtilsUnitTest { @Before public void setup() { diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java similarity index 68% rename from core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java rename to core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java index 208a23eb91..0e3ec29dfd 100644 --- a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java +++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java @@ -7,7 +7,6 @@ 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; @@ -15,13 +14,13 @@ 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 { +import static java.util.stream.Collectors.joining; - 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); +public class EncoderDecoderUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class); + private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253"; private String encodeValue(String value) { String encoded = null; @@ -46,7 +45,7 @@ public class EncoderDecoder { @Test public void givenURL_whenAnalyze_thenCorrect() throws Exception { - URL url = new URL(URL); + URL url = new URL(testUrl); Assert.assertThat(url.getProtocol(), CoreMatchers.is("http")); Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com")); @@ -60,25 +59,25 @@ public class EncoderDecoder { 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; + String encodedURL = requestParams.keySet().stream() + .map(key -> key + "=" + encodeValue(requestParams.get(key))) + .collect(joining("&", "http://www.baeldung.com?", "")); - Assert.assertThat(URL, CoreMatchers.is(encodedURL)); + Assert.assertThat(testUrl, CoreMatchers.is(encodedURL)); } @Test public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception { - URL url = new URL(URL); + URL url = new URL(testUrl); + String query = url.getQuery(); String decodedQuery = Arrays.stream(query.split("&")) - .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) - .collect(Collectors.joining("&")); + .map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])) + .collect(joining("&")); Assert.assertEquals( - "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); + "http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery); } } diff --git a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java rename to core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java index deeebaa240..de60becfce 100644 --- a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java +++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java @@ -9,7 +9,7 @@ import java.util.List; import static junit.framework.TestCase.assertTrue; -public class PizzaTest { +public class PizzaUnitTest { @Test public void givenPizaOrder_whenReady_thenDeliverable() { diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java rename to core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java index e21af9552a..3319716dc6 100644 --- a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java +++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java @@ -1,11 +1,5 @@ package com.baeldung.file; -import org.apache.commons.io.FileUtils; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -20,7 +14,13 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; -public class FileOperationsTest { +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +public class FileOperationsUnitTest { @Test public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { @@ -30,15 +30,15 @@ public class FileOperationsTest { File file = new File(classLoader.getResource("fileTest.txt").getFile()); InputStream inputStream = new FileInputStream(file); String data = readFromInputStream(inputStream); - + Assert.assertEquals(expectedData, data.trim()); } @Test public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - - Class clazz = FileOperationsTest.class; + + Class clazz = FileOperationsUnitTest.class; InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); String data = readFromInputStream(inputStream); @@ -69,44 +69,44 @@ public class FileOperationsTest { Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); } - + @Test public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { String expectedData = "Hello World from fileTest.txt!!!"; - + ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); String data = FileUtils.readFileToString(file); - + Assert.assertEquals(expectedData, data.trim()); } - + @Test public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { String expectedData = "Hello World from fileTest.txt!!!"; Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - + byte[] fileBytes = Files.readAllBytes(path); String data = new String(fileBytes); Assert.assertEquals(expectedData, data.trim()); } - + @Test public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { String expectedData = "Hello World from fileTest.txt!!!"; Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - + StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); lines.forEach(line -> data.append(line).append("\n")); lines.close(); - + Assert.assertEquals(expectedData, data.toString().trim()); } - + private String readFromInputStream(InputStream inputStream) throws IOException { StringBuilder resultStringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java similarity index 89% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java rename to core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index ce878026d4..6f3384c8eb 100644 --- a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -1,5 +1,9 @@ package com.baeldung.functionalinterface; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -10,57 +14,43 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import com.google.common.util.concurrent.Uninterruptibles; import org.junit.Test; -import static org.junit.Assert.*; +import com.google.common.util.concurrent.Uninterruptibles; -public class FunctionalInterfaceTest { +public class FunctionalInterfaceUnitTest { @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", s -> s.length()); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - } @Test public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { - Map nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", String::length); assertEquals(new Integer(4), nameMap.get("John")); assertEquals(new Integer(4), value); - - } - - public byte[] transformArray(short[] array, ShortToByteFunction function) { - byte[] transformedArray = new byte[array.length]; - for (int i = 0; i < array.length; i++) { - transformedArray[i] = function.applyAsByte(array[i]); - } - return transformedArray; } @Test public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() { - short[] array = {(short) 1, (short) 2, (short) 3}; + short[] array = { (short) 1, (short) 2, (short) 3 }; byte[] transformedArray = transformArray(array, s -> (byte) (s * 2)); - byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6}; + byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 }; assertArrayEquals(expectedArray, transformedArray); } @Test public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() { - Map salaries = new HashMap<>(); salaries.put("John", 40000); salaries.put("Freddy", 30000); @@ -71,22 +61,18 @@ public class FunctionalInterfaceTest { assertEquals(new Integer(50000), salaries.get("John")); assertEquals(new Integer(30000), salaries.get("Freddy")); assertEquals(new Integer(60000), salaries.get("Samuel")); - } - @Test public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { - Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); thread.start(); - } @Test public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() { - int[] fibs = {0, 1}; + int[] fibs = { 0, 1 }; Stream fibonacci = Stream.generate(() -> { int result = fibs[1]; int fib3 = fibs[0] + fibs[1]; @@ -95,55 +81,44 @@ public class FunctionalInterfaceTest { return result; }); - List fibonacci5 = fibonacci.limit(5) - .collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); assertEquals(new Integer(2), fibonacci5.get(2)); assertEquals(new Integer(3), fibonacci5.get(3)); assertEquals(new Integer(5), fibonacci5.get(4)); - } @Test public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { - List names = Arrays.asList("John", "Freddy", "Samuel"); names.forEach(name -> System.out.println("Hello, " + name)); - } @Test public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() { - Map ages = new HashMap<>(); ages.put("John", 25); ages.put("Freddy", 24); ages.put("Samuel", 30); ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); - } @Test public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { - List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream() - .filter(name -> name.startsWith("A")) - .collect(Collectors.toList()); + List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); assertTrue(namesWithA.contains("Aaron")); - } @Test public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() { - List names = Arrays.asList("bob", "josh", "megan"); names.replaceAll(String::toUpperCase); @@ -151,7 +126,6 @@ public class FunctionalInterfaceTest { assertEquals("BOB", names.get(0)); assertEquals("JOSH", names.get(1)); assertEquals("MEGAN", names.get(2)); - } @Test @@ -159,8 +133,7 @@ public class FunctionalInterfaceTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream() - .reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); @@ -178,10 +151,6 @@ public class FunctionalInterfaceTest { } - public double squareLazy(Supplier lazyValue) { - return Math.pow(lazyValue.get(), 2); - } - @Test public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() { @@ -196,4 +165,18 @@ public class FunctionalInterfaceTest { } + // + + public double squareLazy(Supplier lazyValue) { + return Math.pow(lazyValue.get(), 2); + } + + public byte[] transformArray(short[] array, ShortToByteFunction function) { + byte[] transformedArray = new byte[array.length]; + for (int i = 0; i < array.length; i++) { + transformedArray[i] = function.applyAsByte(array[i]); + } + return transformedArray; + } + } diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java rename to core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java new file mode 100644 index 0000000000..2ca2d3a0c8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.java.networking.udp; + + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class UDPIntegrationTest { + private EchoClient client; + + @Before + public void setup() throws IOException { + new EchoServer().start(); + client = new EchoClient(); + } + + @Test + public void whenCanSendAndReceivePacket_thenCorrect1() { + String echo = client.sendEcho("hello server"); + assertEquals("hello server", echo); + echo = client.sendEcho("server is working"); + assertFalse(echo.equals("hello server")); + } + + @After + public void tearDown() { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() { + client.sendEcho("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java new file mode 100644 index 0000000000..505d9595ab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java @@ -0,0 +1,104 @@ +package com.baeldung.java.networking.url; + +import static org.junit.Assert.assertEquals; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Test; + +public class UrlUnitTest { + + @Test + public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals("http", url.getProtocol()); + } + + @Test + public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals("baeldung.com", url.getHost()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles?topic=java&version=8", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/guidelines.txt"); + assertEquals("/guidelines.txt", url.getFile()); + } + + @Test + public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java&version=8"); + assertEquals("/articles", url.getPath()); + } + + @Test + public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com/articles?topic=java"); + assertEquals("topic=java", url.getQuery()); + } + + @Test + public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com"); + assertEquals(-1, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException { + final URL url = new URL("http://baeldung.com:8090"); + assertEquals(8090, url.getPort()); + assertEquals(80, url.getDefaultPort()); + } + + @Test + public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException { + final URL baseUrl = new URL("http://baeldung.com"); + final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException { + final URL baseUrl = new URL("http://baeldung.com"); + final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets"); + assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final String file = "/guidelines.txt"; + final URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/guidelines.txt", url.toString()); + } + + @Test + public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final String file = "/articles?topic=java&version=8"; + final URL url = new URL(protocol, host, file); + assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString()); + } + + @Test + public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException { + final String protocol = "http"; + final String host = "baeldung.com"; + final int port = 9000; + final String file = "/guidelines.txt"; + final URL url = new URL(protocol, host, port, file); + assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java rename to core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java index d1ac6df5e4..748dc5b9f4 100644 --- a/core-java/src/test/java/com/baeldung/java/nio/selector/EchoTest.java +++ b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java @@ -6,7 +6,7 @@ import java.io.IOException; import org.junit.Test; -public class EchoTest { +public class NioEchoIntegrationTest { @Test public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException { @@ -16,6 +16,7 @@ public class EchoTest { String resp2 = client.sendMessage("world"); assertEquals("hello", resp1); assertEquals("world", resp2); + process.destroy(); } } diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java deleted file mode 100644 index a12a2f205f..0000000000 --- a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java +++ /dev/null @@ -1,326 +0,0 @@ -package com.baeldung.java.reflection; - -import org.junit.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import static org.junit.Assert.*; - -public class ReflectionTest { - - @Test - public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { - Object person = new Person(); - Field[] fields = person.getClass().getDeclaredFields(); - - List actualFieldNames = getFieldNames(fields); - - assertTrue(Arrays.asList("name", "age") - .containsAll(actualFieldNames)); - } - - @Test - public void givenObject_whenGetsClassName_thenCorrect() { - Object goat = new Goat("goat"); - Class clazz = goat.getClass(); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClassName_whenCreatesObject_thenCorrect() - throws ClassNotFoundException { - Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); - - assertEquals("Goat", clazz.getSimpleName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); - assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); - } - - @Test - public void givenClass_whenRecognisesModifiers_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - int goatMods = goatClass.getModifiers(); - int animalMods = animalClass.getModifiers(); - - assertTrue(Modifier.isPublic(goatMods)); - assertTrue(Modifier.isAbstract(animalMods)); - assertTrue(Modifier.isPublic(animalMods)); - } - - @Test - public void givenClass_whenGetsPackageInfo_thenCorrect() { - Goat goat = new Goat("goat"); - Class goatClass = goat.getClass(); - Package pkg = goatClass.getPackage(); - - assertEquals("com.baeldung.java.reflection", pkg.getName()); - } - - @Test - public void givenClass_whenGetsSuperClass_thenCorrect() { - Goat goat = new Goat("goat"); - String str = "any string"; - - Class goatClass = goat.getClass(); - Class goatSuperClass = goatClass.getSuperclass(); - - assertEquals("Animal", goatSuperClass.getSimpleName()); - assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); - - } - - @Test - public void givenClass_whenGetsImplementedInterfaces_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Class[] goatInterfaces = goatClass.getInterfaces(); - Class[] animalInterfaces = animalClass.getInterfaces(); - - assertEquals(1, goatInterfaces.length); - assertEquals(1, animalInterfaces.length); - assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); - assertEquals("Eating", animalInterfaces[0].getSimpleName()); - } - - @Test - public void givenClass_whenGetsConstructor_thenCorrect() - throws ClassNotFoundException { - Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); - Constructor[] constructors = goatClass.getConstructors(); - - assertEquals(1, constructors.length); - assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); - } - - @Test - public void givenClass_whenGetsFields_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Field[] fields = animalClass.getDeclaredFields(); - - List actualFields = getFieldNames(fields); - - assertEquals(2, actualFields.size()); - assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); - } - - @Test - public void givenClass_whenGetsMethods_thenCorrect() - throws ClassNotFoundException { - Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); - Method[] methods = animalClass.getDeclaredMethods(); - List actualMethods = getMethodNames(methods); - - assertEquals(4, actualMethods.size()); - assertTrue(actualMethods.containsAll(Arrays.asList("getName", - "setName", "getSound"))); - } - - @Test - public void givenClass_whenGetsAllConstructors_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Constructor[] constructors = birdClass.getConstructors(); - - assertEquals(3, constructors.length); - } - - @Test - public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - } - - @Test - public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - - Constructor cons1 = birdClass.getConstructor(); - Constructor cons2 = birdClass.getConstructor(String.class); - Constructor cons3 = birdClass.getConstructor(String.class, - boolean.class); - - Bird bird1 = (Bird) cons1.newInstance(); - Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); - Bird bird3 = (Bird) cons3.newInstance("dove", true); - - assertEquals("bird", bird1.getName()); - assertEquals("Weaver bird", bird2.getName()); - assertEquals("dove", bird3.getName()); - assertFalse(bird1.walks()); - assertTrue(bird3.walks()); - } - - @Test - public void givenClass_whenGetsPublicFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field[] fields = birdClass.getFields(); - assertEquals(1, fields.length); - assertEquals("CATEGORY", fields[0].getName()); - - } - - @Test - public void givenClass_whenGetsPublicFieldByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - assertEquals("CATEGORY", field.getName()); - - } - - @Test - public void givenClass_whenGetsDeclaredFields_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field[] fields = birdClass.getDeclaredFields(); - assertEquals(1, fields.length); - assertEquals("walks", fields[0].getName()); - } - - @Test - public void givenClass_whenGetsFieldsByName_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getDeclaredField("walks"); - assertEquals("walks", field.getName()); - - } - - @Test - public void givenClassField_whenGetsType_thenCorrect() - throws Exception { - Field field = Class.forName("com.baeldung.java.reflection.Bird") - .getDeclaredField("walks"); - Class fieldClass = field.getType(); - assertEquals("boolean", fieldClass.getSimpleName()); - } - - @Test - public void givenClassField_whenSetsAndGetsValue_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Field field = birdClass.getDeclaredField("walks"); - field.setAccessible(true); - - assertFalse(field.getBoolean(bird)); - assertFalse(bird.walks()); - - field.set(bird, true); - - assertTrue(field.getBoolean(bird)); - assertTrue(bird.walks()); - - } - - @Test - public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Field field = birdClass.getField("CATEGORY"); - field.setAccessible(true); - - assertEquals("domestic", field.get(null)); - } - - @Test - public void givenClass_whenGetsAllPublicMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Method[] methods = birdClass.getMethods(); - List methodNames = getMethodNames(methods); - - assertTrue(methodNames.containsAll(Arrays - .asList("equals", "notifyAll", "hashCode", - "walks", "eats", "toString"))); - - } - - @Test - public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() - throws ClassNotFoundException { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); - - List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); - - assertEquals(expectedMethodNames.size(), actualMethodNames.size()); - assertTrue(expectedMethodNames.containsAll(actualMethodNames)); - assertTrue(actualMethodNames.containsAll(expectedMethodNames)); - - } - - @Test - public void givenMethodName_whenGetsMethod_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - - assertFalse(walksMethod.isAccessible()); - assertFalse(setWalksMethod.isAccessible()); - - walksMethod.setAccessible(true); - setWalksMethod.setAccessible(true); - - assertTrue(walksMethod.isAccessible()); - assertTrue(setWalksMethod.isAccessible()); - - } - - @Test - public void givenMethod_whenInvokes_thenCorrect() - throws Exception { - Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); - Bird bird = (Bird) birdClass.newInstance(); - Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", - boolean.class); - Method walksMethod = birdClass.getDeclaredMethod("walks"); - boolean walks = (boolean) walksMethod.invoke(bird); - - assertFalse(walks); - assertFalse(bird.walks()); - - setWalksMethod.invoke(bird, true); - boolean walks2 = (boolean) walksMethod.invoke(bird); - - assertTrue(walks2); - assertTrue(bird.walks()); - - } - - private static List getFieldNames(Field[] fields) { - List fieldNames = new ArrayList<>(); - for (Field field : fields) - fieldNames.add(field.getName()); - return fieldNames; - - } - - private static List getMethodNames(Method[] methods) { - List methodNames = new ArrayList<>(); - for (Method method : methods) - methodNames.add(method.getName()); - return methodNames; - } - -} diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java new file mode 100644 index 0000000000..0c090901e7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java @@ -0,0 +1,302 @@ +package com.baeldung.java.reflection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class ReflectionUnitTest { + + @Test + public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() { + final Object person = new Person(); + final Field[] fields = person.getClass().getDeclaredFields(); + + final List actualFieldNames = getFieldNames(fields); + + assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames)); + } + + @Test + public void givenObject_whenGetsClassName_thenCorrect() { + final Object goat = new Goat("goat"); + final Class clazz = goat.getClass(); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException { + final Class clazz = Class.forName("com.baeldung.java.reflection.Goat"); + + assertEquals("Goat", clazz.getSimpleName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getName()); + assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName()); + } + + @Test + public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final int goatMods = goatClass.getModifiers(); + final int animalMods = animalClass.getModifiers(); + + assertTrue(Modifier.isPublic(goatMods)); + assertTrue(Modifier.isAbstract(animalMods)); + assertTrue(Modifier.isPublic(animalMods)); + } + + @Test + public void givenClass_whenGetsPackageInfo_thenCorrect() { + final Goat goat = new Goat("goat"); + final Class goatClass = goat.getClass(); + final Package pkg = goatClass.getPackage(); + + assertEquals("com.baeldung.java.reflection", pkg.getName()); + } + + @Test + public void givenClass_whenGetsSuperClass_thenCorrect() { + final Goat goat = new Goat("goat"); + final String str = "any string"; + + final Class goatClass = goat.getClass(); + final Class goatSuperClass = goatClass.getSuperclass(); + + assertEquals("Animal", goatSuperClass.getSimpleName()); + assertEquals("Object", str.getClass().getSuperclass().getSimpleName()); + + } + + @Test + public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Class[] goatInterfaces = goatClass.getInterfaces(); + final Class[] animalInterfaces = animalClass.getInterfaces(); + + assertEquals(1, goatInterfaces.length); + assertEquals(1, animalInterfaces.length); + assertEquals("Locomotion", goatInterfaces[0].getSimpleName()); + assertEquals("Eating", animalInterfaces[0].getSimpleName()); + } + + @Test + public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException { + final Class goatClass = Class.forName("com.baeldung.java.reflection.Goat"); + final Constructor[] constructors = goatClass.getConstructors(); + + assertEquals(1, constructors.length); + assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName()); + } + + @Test + public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException { + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Field[] fields = animalClass.getDeclaredFields(); + + final List actualFields = getFieldNames(fields); + + assertEquals(2, actualFields.size()); + assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY"))); + } + + @Test + public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException { + final Class animalClass = Class.forName("com.baeldung.java.reflection.Animal"); + final Method[] methods = animalClass.getDeclaredMethods(); + final List actualMethods = getMethodNames(methods); + + assertEquals(3, actualMethods.size()); + assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound"))); + } + + @Test + public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Constructor[] constructors = birdClass.getConstructors(); + + assertEquals(3, constructors.length); + } + + @Test + public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + birdClass.getConstructor(); + birdClass.getConstructor(String.class); + birdClass.getConstructor(String.class, boolean.class); + } + + @Test + public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + + final Constructor cons1 = birdClass.getConstructor(); + final Constructor cons2 = birdClass.getConstructor(String.class); + final Constructor cons3 = birdClass.getConstructor(String.class, boolean.class); + + final Bird bird1 = (Bird) cons1.newInstance(); + final Bird bird2 = (Bird) cons2.newInstance("Weaver bird"); + final Bird bird3 = (Bird) cons3.newInstance("dove", true); + + assertEquals("bird", bird1.getName()); + assertEquals("Weaver bird", bird2.getName()); + assertEquals("dove", bird3.getName()); + assertFalse(bird1.walks()); + assertTrue(bird3.walks()); + } + + @Test + public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field[] fields = birdClass.getFields(); + assertEquals(1, fields.length); + assertEquals("CATEGORY", fields[0].getName()); + + } + + @Test + public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getField("CATEGORY"); + assertEquals("CATEGORY", field.getName()); + + } + + @Test + public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field[] fields = birdClass.getDeclaredFields(); + assertEquals(1, fields.length); + assertEquals("walks", fields[0].getName()); + } + + @Test + public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getDeclaredField("walks"); + assertEquals("walks", field.getName()); + + } + + @Test + public void givenClassField_whenGetsType_thenCorrect() throws Exception { + final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks"); + final Class fieldClass = field.getType(); + assertEquals("boolean", fieldClass.getSimpleName()); + } + + @Test + public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Bird bird = (Bird) birdClass.newInstance(); + final Field field = birdClass.getDeclaredField("walks"); + field.setAccessible(true); + + assertFalse(field.getBoolean(bird)); + assertFalse(bird.walks()); + + field.set(bird, true); + + assertTrue(field.getBoolean(bird)); + assertTrue(bird.walks()); + + } + + @Test + public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Field field = birdClass.getField("CATEGORY"); + field.setAccessible(true); + + assertEquals("domestic", field.get(null)); + } + + @Test + public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Method[] methods = birdClass.getMethods(); + final List methodNames = getMethodNames(methods); + + assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString"))); + + } + + @Test + public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods()); + + final List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats"); + + assertEquals(expectedMethodNames.size(), actualMethodNames.size()); + assertTrue(expectedMethodNames.containsAll(actualMethodNames)); + assertTrue(actualMethodNames.containsAll(expectedMethodNames)); + + } + + @Test + public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Method walksMethod = birdClass.getDeclaredMethod("walks"); + final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); + + assertFalse(walksMethod.isAccessible()); + assertFalse(setWalksMethod.isAccessible()); + + walksMethod.setAccessible(true); + setWalksMethod.setAccessible(true); + + assertTrue(walksMethod.isAccessible()); + assertTrue(setWalksMethod.isAccessible()); + + } + + @Test + public void givenMethod_whenInvokes_thenCorrect() throws Exception { + final Class birdClass = Class.forName("com.baeldung.java.reflection.Bird"); + final Bird bird = (Bird) birdClass.newInstance(); + final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class); + final Method walksMethod = birdClass.getDeclaredMethod("walks"); + final boolean walks = (boolean) walksMethod.invoke(bird); + + assertFalse(walks); + assertFalse(bird.walks()); + + setWalksMethod.invoke(bird, true); + final boolean walks2 = (boolean) walksMethod.invoke(bird); + + assertTrue(walks2); + assertTrue(bird.walks()); + + } + + private static List getFieldNames(Field[] fields) { + final List fieldNames = new ArrayList<>(); + for (final Field field : fields) { + fieldNames.add(field.getName()); + } + return fieldNames; + + } + + private static List getMethodNames(Method[] methods) { + final List methodNames = new ArrayList<>(); + for (final Method method : methods) { + methodNames.add(method.getName()); + } + return methodNames; + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/regex/RegexTest.java rename to core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java index 414401eb85..e4ea55aae3 100644 --- a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java @@ -7,7 +7,7 @@ import java.util.regex.Pattern; import org.junit.Test; -public class RegexTest { +public class RegexUnitTest { private static Pattern pattern; private static Matcher matcher; @@ -499,4 +499,3 @@ public class RegexTest { return matches; } } - diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java index 21a5e34b9b..5b07b3e3ae 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class Java8DefaultStaticIntefaceMethodsTest { +public class Java8DefaultStaticIntefaceMethodsUnitTest { @Test public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java similarity index 83% rename from core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java index 581ccec182..41eb864fd9 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java @@ -1,17 +1,26 @@ package com.baeldung.java8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; - -import static org.junit.Assert.*; - - -public class Java8ExecutorServiceTest { +public class Java8ExecutorServiceIntegrationTest { private Runnable runnableTask; private Callable callableTask; @@ -53,9 +62,7 @@ public class Java8ExecutorServiceTest { @Test public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() { - ExecutorService threadPoolExecutor = - new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>()); + ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); for (int i = 0; i < 100; i++) { threadPoolExecutor.submit(callableTask); @@ -138,8 +145,7 @@ public class Java8ExecutorServiceTest { @Test public void submittingTaskScheduling_whenExecuted_thenCorrect() { - ScheduledExecutorService executorService = Executors - .newSingleThreadScheduledExecutor(); + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS); String result = null; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java similarity index 94% rename from core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java index 273b2d78db..6778fd782b 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java @@ -1,18 +1,20 @@ package com.baeldung.java8; - -import com.baeldung.forkjoin.CustomRecursiveAction; -import com.baeldung.forkjoin.CustomRecursiveTask; -import com.baeldung.forkjoin.util.PoolUtil; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Random; import java.util.concurrent.ForkJoinPool; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; -public class Java8ForkJoinTest { +import com.baeldung.forkjoin.CustomRecursiveAction; +import com.baeldung.forkjoin.CustomRecursiveTask; +import com.baeldung.forkjoin.util.PoolUtil; + +public class Java8ForkJoinIntegrationTest { private int[] arr; private CustomRecursiveTask customRecursiveTask; @@ -27,28 +29,23 @@ public class Java8ForkJoinTest { customRecursiveTask = new CustomRecursiveTask(arr); } - @Test public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() { - ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool; ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool; assertNotNull(forkJoinPool); assertEquals(2, forkJoinPool.getParallelism()); assertEquals(forkJoinPool, forkJoinPoolTwo); - } @Test public void callCommonPool_whenExistsAndExpectedType_thenCorrect() { - ForkJoinPool commonPool = ForkJoinPool.commonPool(); ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool(); assertNotNull(commonPool); assertEquals(commonPool, commonPoolTwo); - } @Test @@ -63,7 +60,6 @@ public class Java8ForkJoinTest { @Test public void executeRecursiveTask_whenExecuted_thenCorrect() { - ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); forkJoinPool.execute(customRecursiveTask); @@ -73,12 +69,10 @@ public class Java8ForkJoinTest { forkJoinPool.submit(customRecursiveTask); int resultTwo = customRecursiveTask.join(); assertTrue(customRecursiveTask.isDone()); - } @Test public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() { - CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr); CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr); CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr); @@ -95,6 +89,6 @@ public class Java8ForkJoinTest { assertTrue(customRecursiveTaskSecond.isDone()); assertTrue(customRecursiveTaskLast.isDone()); assertTrue(result != 0); - } + } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java index faaf3ae407..13ddcc805f 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java @@ -11,7 +11,7 @@ import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class Java8FunctionalInteracesLambdasTest { +public class Java8FunctionalInteracesLambdasUnitTest { private UseFoo useFoo; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java index d9d88c5052..2dc1fe18e6 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java @@ -12,7 +12,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class Java8MethodReferenceTest { +public class Java8MethodReferenceUnitTest { private List list; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java similarity index 80% rename from core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java index 26de39bc0e..c6d5836387 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java @@ -1,16 +1,23 @@ package com.baeldung.java8; -import com.baeldung.java_8_features.*; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; -public class Java8OptionalTest { +import com.baeldung.java_8_features.Address; +import com.baeldung.java_8_features.CustomException; +import com.baeldung.java_8_features.OptionalAddress; +import com.baeldung.java_8_features.OptionalUser; +import com.baeldung.java_8_features.User; + +public class Java8OptionalUnitTest { private List list; @@ -32,7 +39,6 @@ public class Java8OptionalTest { @Test public void checkOptional_whenAsExpected_thenCorrect() { - Optional optionalEmpty = Optional.empty(); assertFalse(optionalEmpty.isPresent()); @@ -52,27 +58,19 @@ public class Java8OptionalTest { assertTrue(listOptNull.isEmpty()); Optional user = Optional.ofNullable(getUser()); - String result = user.map(User::getAddress) - .map(Address::getStreet) - .orElse("not specified"); + String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified"); assertEquals(result, "1st Avenue"); Optional optionalUser = Optional.ofNullable(getOptionalUser()); - String resultOpt = optionalUser.flatMap(OptionalUser::getAddress) - .flatMap(OptionalAddress::getStreet) - .orElse("not specified"); + String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified"); assertEquals(resultOpt, "1st Avenue"); Optional userNull = Optional.ofNullable(getUserNull()); - String resultNull = userNull.map(User::getAddress) - .map(Address::getStreet) - .orElse("not specified"); + String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified"); assertEquals(resultNull, "not specified"); Optional optionalUserNull = Optional.ofNullable(getOptionalUserNull()); - String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress) - .flatMap(OptionalAddress::getStreet) - .orElse("not specified"); + String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified"); assertEquals(resultOptNull, "not specified"); } diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java similarity index 99% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java index 37326c6d26..d9a72063af 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java @@ -17,11 +17,11 @@ import java.util.stream.*; import static org.junit.Assert.*; -public class Java8StreamApiTest { +public class Java8StreamApiUnitTest { private long counter; - private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class); + private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class); private List productList; diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java rename to core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java index 1f1dda49ce..fc83553c6e 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java @@ -14,7 +14,7 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -public class Java8StreamsTest { +public class Java8StreamsUnitTest { private List list; diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java similarity index 79% rename from core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java rename to core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index f2e7452137..68b736096e 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -1,21 +1,25 @@ package com.baeldung.java8; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; -import java.nio.file.*; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.text.DecimalFormat; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; -import static org.junit.Assert.assertEquals; - -public class JavaFolderSizeTest { +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +public class JavaFolderSizeUnitTest { + private final long EXPECTED_SIZE = 381; private String path; @Before @@ -26,18 +30,14 @@ public class JavaFolderSizeTest { @Test public void whenGetFolderSizeRecursive_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final long size = getFolderSize(folder); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException { - final long expectedSize = 136; - final AtomicLong size = new AtomicLong(0); final Path folder = Paths.get(path); @@ -49,41 +49,33 @@ public class JavaFolderSizeTest { } }); - assertEquals(expectedSize, size.longValue()); + assertEquals(EXPECTED_SIZE, size.longValue()); } @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { - final long expectedSize = 136; - final Path folder = Paths.get(path); final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final long size = FileUtils.sizeOfDirectory(folder); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test public void whenGetFolderSizeUsingGuava_thenCorrect() { - final long expectedSize = 136; - final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false) - .filter(File::isFile) - .mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); - assertEquals(expectedSize, size); + assertEquals(EXPECTED_SIZE, size); } @Test @@ -91,19 +83,19 @@ public class JavaFolderSizeTest { final File folder = new File(path); final long size = getFolderSize(folder); - final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"}; + final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; final int unitIndex = (int) (Math.log10(size) / 3); final double unitValue = 1 << (unitIndex * 10); final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex]; - assertEquals("136 B", readableSize); + assertEquals(EXPECTED_SIZE + " B", readableSize); } private long getFolderSize(final File folder) { long length = 0; final File[] files = folder.listFiles(); - for (File file : files) { + for (final File file : files) { if (file.isFile()) { length += file.length(); } else { diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java rename to core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java index 224c4e9d6a..4c843ccaaf 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java @@ -8,7 +8,7 @@ import java.io.StringWriter; import java.util.Date; import java.util.Scanner; -public class JavaTryWithResourcesTest { +public class JavaTryWithResourcesUnitTest { private static final String TEST_STRING_HELLO_WORLD = "Hello World"; private Date resource1Date, resource2Date; diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java rename to core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java index 164a571817..7889e6ad53 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java @@ -7,7 +7,7 @@ import java.io.UnsupportedEncodingException; import static org.junit.Assert.*; -public class ApacheCommonsEncodeDecodeTest { +public class ApacheCommonsEncodeDecodeUnitTest { // tests diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java rename to core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java index 18dccf71ba..62cfa4c0a1 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java @@ -8,7 +8,7 @@ import java.util.UUID; import static org.junit.Assert.*; -public class Java8EncodeDecodeTest { +public class Java8EncodeDecodeUnitTest { // tests diff --git a/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java b/core-java/src/test/java/com/baeldung/java8/entity/Human.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/entity/Human.java rename to core-java/src/test/java/com/baeldung/java8/entity/Human.java diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java similarity index 79% rename from core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java rename to core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java index 895f514f4a..13609b6977 100644 --- a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotTest.java +++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java @@ -7,10 +7,9 @@ import java.io.File; import static org.junit.Assert.assertTrue; +public class ScreenshotIntegrationTest { -public class ScreenshotTest { - - private Screenshot screenshot = new Screenshot("", "Screenshot", "jpg"); + private Screenshot screenshot = new Screenshot("Screenshot.jpg"); private File file = new File("Screenshot.jpg"); @Test diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java new file mode 100644 index 0000000000..7ac8e0a97a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.socket; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.Executors; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class EchoIntegrationTest { + private static final Integer PORT = 4444; + + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Thread.sleep(500); + } + + private EchoClient client = new EchoClient(); + + @Before + public void init() { + client.startConnection("127.0.0.1", PORT); + } + + @After + public void tearDown() { + client.stopConnection(); + } + + // + + @Test + public void givenClient_whenServerEchosMessage_thenCorrect() { + String resp1 = client.sendMessage("hello"); + String resp2 = client.sendMessage("world"); + String resp3 = client.sendMessage("!"); + String resp4 = client.sendMessage("."); + assertEquals("hello", resp1); + assertEquals("world", resp2); + assertEquals("!", resp3); + assertEquals("good bye", resp4); + } + +} diff --git a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java similarity index 65% rename from sockets/src/test/java/com/baeldung/socket/GreetServerTest.java rename to core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index fedc32fb39..06b37d8539 100644 --- a/sockets/src/test/java/com/baeldung/socket/GreetServerTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -2,24 +2,29 @@ package com.baeldung.socket; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.Executors; import static org.junit.Assert.assertEquals; -public class GreetServerTest { +public class GreetServerIntegrationTest { - GreetClient client; + private GreetClient client; - { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666)); + private static final Integer PORT = 6666; + + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Thread.sleep(500); } @Before public void init() { client = new GreetClient(); - client.startConnection("127.0.0.1", 6666); + client.startConnection("127.0.0.1", PORT); } diff --git a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java new file mode 100644 index 0000000000..6ebc0946c5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java @@ -0,0 +1,59 @@ +package com.baeldung.socket; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +public class SocketEchoMultiIntegrationTest { + + private static final Integer PORT = 5555; + + @BeforeClass + public static void start() throws InterruptedException { + Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT)); + Thread.sleep(500); + } + + @Test + public void givenClient1_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + + @Test + public void givenClient2_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } + + @Test + public void givenClient3_whenServerResponds_thenCorrect() { + EchoClient client = new EchoClient(); + client.startConnection("127.0.0.1", PORT); + String msg1 = client.sendMessage("hello"); + String msg2 = client.sendMessage("world"); + String terminate = client.sendMessage("."); + assertEquals(msg1, "hello"); + assertEquals(msg2, "world"); + assertEquals(terminate, "bye"); + client.stopConnection(); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java similarity index 86% rename from core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java rename to core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index df336f4a93..a62ec99043 100644 --- a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -1,13 +1,23 @@ package com.baeldung.threadpool; -import java.util.concurrent.*; +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class CoreThreadPoolTest { +public class CoreThreadPoolIntegrationTest { @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { @@ -132,9 +142,7 @@ public class CoreThreadPoolTest { @Test public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() { - TreeNode tree = new TreeNode(5, - new TreeNode(3), new TreeNode(2, - new TreeNode(2), new TreeNode(8))); + TreeNode tree = new TreeNode(5, new TreeNode(3), new TreeNode(2, new TreeNode(2), new TreeNode(8))); ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); int sum = forkJoinPool.invoke(new CountingTask(tree)); @@ -142,5 +150,4 @@ public class CoreThreadPoolTest { assertEquals(20, sum); } - } diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java rename to core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java index 92e0f9a8cb..fd13a4fd78 100644 --- a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class GuavaThreadPoolTest { +public class GuavaThreadPoolIntegrationTest { @Test public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() { diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java similarity index 85% rename from core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java rename to core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index da9027060e..3ad3deb548 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,41 +1,43 @@ -package com.baeldung.util; - -import org.junit.Test; - -import java.time.*; -import java.time.temporal.ChronoField; - -import static org.junit.Assert.assertEquals; - -public class CurrentDateTimeTest { - - private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC")); - - @Test - public void shouldReturnCurrentDate() { - - final LocalDate now = LocalDate.now(clock); - - assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); - assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); - assertEquals(2016, now.get(ChronoField.YEAR)); - } - - @Test - public void shouldReturnCurrentTime() { - - final LocalTime now = LocalTime.now(clock); - - assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); - assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); - assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); - } - - @Test - public void shouldReturnCurrentTimestamp() { - - final Instant now = Instant.now(clock); - - assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); - } -} +package com.baeldung.util; + +import static org.junit.Assert.assertEquals; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.temporal.ChronoField; + +import org.junit.Test; + +public class CurrentDateTimeUnitTest { + + private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC")); + + @Test + public void shouldReturnCurrentDate() { + final LocalDate now = LocalDate.now(clock); + + assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(2016, now.get(ChronoField.YEAR)); + } + + @Test + public void shouldReturnCurrentTime() { + final LocalTime now = LocalTime.now(clock); + + assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); + } + + @Test + public void shouldReturnCurrentTimestamp() { + final Instant now = Instant.now(clock); + + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java similarity index 87% rename from core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java rename to core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java index 23be2200d3..e615e6a7d1 100644 --- a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java @@ -1,13 +1,17 @@ package org.baeldung.core.exceptions; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + import org.apache.log4j.Logger; import org.junit.Test; -import java.io.*; +public class FileNotFoundExceptionUnitTest { -public class FileNotFoundExceptionTest { - - private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class); + private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class); private String fileName = Double.toString(Math.random()); @@ -42,7 +46,7 @@ public class FileNotFoundExceptionTest { LOG.error("Optional file " + fileName + " was not found.", ex); } } - + private void readFailingFile() throws IOException { BufferedReader rd = new BufferedReader(new FileReader(new File(fileName))); rd.readLine(); diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java similarity index 83% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java index 75d96e5989..e4866d0078 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java @@ -2,22 +2,22 @@ package org.baeldung.equalshashcode.entities; import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import org.junit.Assert; import org.junit.Test; -public class ComplexClassTest { +public class ComplexClassUnitTest { @Test public void testEqualsAndHashcodes() { - - ArrayList strArrayList = new ArrayList(); + List strArrayList = new ArrayList(); strArrayList.add("abc"); strArrayList.add("def"); ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45, 67)); ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45, 67)); - ArrayList strArrayListD = new ArrayList(); + List strArrayListD = new ArrayList(); strArrayListD.add("lmn"); strArrayListD.add("pqr"); ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45, 67)); diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java index 16f25ae021..603b0bfbf9 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java @@ -3,7 +3,7 @@ package org.baeldung.equalshashcode.entities; import org.junit.Assert; import org.junit.Test; -public class PrimitiveClassTest { +public class PrimitiveClassUnitTest { @Test public void testTwoEqualsObjects() { diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java rename to core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java index 52d024a696..0943436883 100644 --- a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassTest.java +++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java @@ -5,11 +5,10 @@ import java.awt.Color; import org.junit.Assert; import org.junit.Test; -public class SquareClassTest { +public class SquareClassUnitTest { @Test public void testEqualsAndHashcodes() { - Square aObject = new Square(10, Color.BLUE); Square bObject = new Square(10, Color.BLUE); diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java similarity index 97% rename from core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index ff92410bc4..3ab8e1de91 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -7,6 +7,7 @@ import java.util.Scanner; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; +import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,7 +15,8 @@ import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; -public class JavaIoIntegrationTest { +@Ignore("need large file for testing") +public class JavaIoUnitTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); // tests - iterate lines in a file diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java rename to core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index fcc74dbe64..da316aa885 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -public class JavaTimerUnitTest { +public class JavaTimerLongRunningUnitTest { // tests diff --git a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java index ad1f2dc70c..885c3bcd6c 100644 --- a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java @@ -7,11 +7,11 @@ import org.junit.Test; public class ArraysJoinAndSplitJUnitTest { - private final String[] sauces = {"Marinara", "Olive Oil"}; - private final String[] cheeses = {"Mozzarella", "Feta", "Parmesan"}; - private final String[] vegetables = {"Olives", "Spinach", "Green Peppers"}; + private final String[] sauces = { "Marinara", "Olive Oil" }; + private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" }; + private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" }; - private final String[] customers = {"Jay", "Harry", "Ronnie", "Gary", "Ross"}; + private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" }; @Test public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() { @@ -25,12 +25,9 @@ public class ArraysJoinAndSplitJUnitTest { System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length); - Assert.assertArrayEquals(toppings, - new String[]{"Marinara", "Olive Oil", "Mozzarella", "Feta", - "Parmesan", "Olives", "Spinach", "Green Peppers"}); + Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" }); } - @Test public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() { int ordersHalved = (customers.length / 2) + (customers.length % 2); @@ -38,7 +35,7 @@ public class ArraysJoinAndSplitJUnitTest { String[] driverOne = Arrays.copyOf(customers, ordersHalved); String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length); - Assert.assertArrayEquals(driverOne, new String[]{"Jay", "Harry", "Ronnie"}); - Assert.assertArrayEquals(driverTwo, new String[]{"Gary", "Ross"}); + Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" }); + Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" }); } } diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java similarity index 85% rename from core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java rename to core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java index 30b0111555..5d07628a96 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/ArrayListTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java @@ -12,16 +12,13 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.*; -public class ArrayListTest { +public class ArrayListUnitTest { private List stringsToSearch; @Before public void setUp() { - List list = LongStream.range(0, 16) - .boxed() - .map(Long::toHexString) - .collect(toCollection(ArrayList::new)); + List list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new)); stringsToSearch = new ArrayList<>(list); stringsToSearch.addAll(list); } @@ -34,8 +31,7 @@ public class ArrayListTest { @Test public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() { - Collection numbers = - IntStream.range(0, 10).boxed().collect(toSet()); + Collection numbers = IntStream.range(0, 10).boxed().collect(toSet()); List list = new ArrayList<>(numbers); assertEquals(10, list.size()); @@ -56,8 +52,7 @@ public class ArrayListTest { @Test public void givenCollection_whenAddToArrayList_thenIsAdded() { List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); - LongStream.range(4, 10).boxed() - .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); + LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys))); assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list)); } @@ -88,10 +83,7 @@ public class ArrayListTest { public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() { Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9")); - List result = stringsToSearch - .stream() - .filter(matchingStrings::contains) - .collect(toCollection(ArrayList::new)); + List result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new)); assertEquals(6, result.size()); } @@ -131,8 +123,7 @@ public class ArrayListTest { @Test public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() { - Set matchingStrings - = Sets.newHashSet("a", "b", "c", "d", "e", "f"); + Set matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f"); Iterator it = stringsToSearch.iterator(); while (it.hasNext()) { diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java similarity index 60% rename from core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java rename to core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java index a6814ee600..cc042eeca9 100644 --- a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java @@ -1,21 +1,21 @@ package org.baeldung.java.enums; - -import com.baeldung.enums.Pizza; -import org.junit.Test; +import static junit.framework.TestCase.assertTrue; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; -import static junit.framework.TestCase.assertTrue; +import org.junit.Test; +import com.baeldung.enums.Pizza; + +public class PizzaUnitTest { -public class PizzaTest { @Test public void givenPizaOrder_whenReady_thenDeliverable() { Pizza testPz = new Pizza(); - testPz.setStatus(Pizza.PizzaStatus.READY); + testPz.setStatus(Pizza.PizzaStatusEnum.READY); assertTrue(testPz.isDeliverable()); } @@ -23,16 +23,16 @@ public class PizzaTest { public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); @@ -48,33 +48,34 @@ public class PizzaTest { List pzList = new ArrayList<>(); Pizza pz1 = new Pizza(); - pz1.setStatus(Pizza.PizzaStatus.DELIVERED); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); Pizza pz2 = new Pizza(); - pz2.setStatus(Pizza.PizzaStatus.ORDERED); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz3 = new Pizza(); - pz3.setStatus(Pizza.PizzaStatus.ORDERED); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); Pizza pz4 = new Pizza(); - pz4.setStatus(Pizza.PizzaStatus.READY); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); pzList.add(pz1); pzList.add(pz2); pzList.add(pz3); pzList.add(pz4); - EnumMap> map = Pizza.groupPizzaByStatus(pzList); - assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1); - assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2); - assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1); + EnumMap> map = Pizza.groupPizzaByStatus(pzList); + assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); + assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); + assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); } @Test public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { Pizza pz = new Pizza(); - pz.setStatus(Pizza.PizzaStatus.READY); + pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.deliver(); - assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED); + assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); } + } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java similarity index 88% rename from core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java index 24213ba869..f4c52f3c65 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java @@ -13,7 +13,7 @@ import java.nio.file.Paths; import org.apache.commons.io.FileUtils; import org.junit.Test; -public class JavaFileIntegrationTest { +public class JavaFileUnitTest { // create a file @@ -46,7 +46,7 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException { final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt"); - fileToMove.exists(); + fileToMove.createNewFile();// .exists(); final File destDir = new File("src/test/resources/"); destDir.mkdir(); @@ -68,7 +68,7 @@ public class JavaFileIntegrationTest { public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException { final File fileToMove = new File("src/test/resources/fileToMove.txt"); fileToMove.createNewFile(); - final File destDir = new File("src/test/resources/"); + final File destDir = new File("src/main/resources/"); final File targetFile = new File(destDir, fileToMove.getName()); com.google.common.io.Files.createParentDirs(targetFile); com.google.common.io.Files.move(fileToMove, targetFile); @@ -76,13 +76,13 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException { - FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/test/resources/fileMoved.txt")); + FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt")); } @Test public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove.txt")); - FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true); + FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); + FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true); } // delete a file @@ -99,7 +99,7 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { - // Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); Files.delete(fileToDeletePath); @@ -117,7 +117,7 @@ public class JavaFileIntegrationTest { @Test public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { - // FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java similarity index 97% rename from core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index e679b82d3f..b1aa58424d 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -23,7 +23,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaReadFromFileTest { +public class JavaReadFromFileUnitTest { @Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { @@ -115,7 +115,7 @@ public class JavaReadFromFileTest { final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); - + System.out.println(currentLine); assertEquals(expected_value, currentLine); } @@ -143,8 +143,9 @@ public class JavaReadFromFileTest { final FileChannel channel = reader.getChannel(); int bufferSize = 1024; - if (bufferSize > channel.size()) + if (bufferSize > channel.size()) { bufferSize = (int) channel.size(); + } final ByteBuffer buff = ByteBuffer.allocate(bufferSize); channel.read(buff); buff.flip(); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 61f0f52316..5af286dbca 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -15,7 +15,7 @@ import java.util.Scanner; import org.junit.Test; -public class JavaScannerTest { +public class JavaScannerUnitTest { @Test public void whenReadFileWithScanner_thenCorrect() throws IOException { diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java similarity index 99% rename from core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java rename to core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java index 93cfffa39d..9ff95c4e16 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java @@ -26,7 +26,7 @@ import java.nio.file.Paths; import org.junit.Test; -public class JavaWriteToFileTest { +public class JavaWriteToFileUnitTest { private String fileName = "src/test/resources/test_write.txt"; private String fileName1 = "src/test/resources/test_write_1.txt"; diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java similarity index 83% rename from core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java index b8926946a9..c609f5badb 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListAssertJTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ListAssertJTest { +public class ListAssertJUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); @@ -15,9 +15,7 @@ public class ListAssertJTest { @Test public void whenTestingForEquality_ShouldBeEqual() throws Exception { - assertThat(list1) - .isEqualTo(list2) - .isNotEqualTo(list3); + assertThat(list1).isEqualTo(list2).isNotEqualTo(list3); assertThat(list1.equals(list2)).isTrue(); assertThat(list1.equals(list3)).isFalse(); diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java similarity index 94% rename from core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java rename to core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java index fa80d0e224..b7c2bd7272 100644 --- a/core-java/src/test/java/org/baeldung/java/lists/ListTestNGTest.java +++ b/core-java/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java @@ -6,7 +6,7 @@ import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; -public class ListTestNGTest { +public class ListTestNgUnitTest { private final List list1 = Arrays.asList("1", "2", "3", "4"); private final List list2 = Arrays.asList("1", "2", "3", "4"); diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java similarity index 77% rename from core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java rename to core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java index 83f1fb33b6..55e71470c8 100644 --- a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java @@ -1,9 +1,10 @@ package org.baeldung.java.md5; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; +import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -11,80 +12,64 @@ import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; import org.apache.commons.codec.digest.DigestUtils; -import org.junit.Before; import org.junit.Test; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; -import java.io.File; -import java.io.IOException; -import java.nio.*; -import static org.assertj.core.api.Assertions.assertThat; +public class JavaMD5UnitTest { - -public class JavaMD5Test { - - String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - - - + @Test public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); - + assertThat(myHash.equals(hash)).isTrue(); } - + @Test public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - + MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Files.readAllBytes(Paths.get(filename))); byte[] digest = md.digest(); - String myChecksum = DatatypeConverter - .printHexBinary(digest).toUpperCase(); - + String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - + @Test - public void givenPassword_whenHashingUsingCommons_thenVerifying() { + public void givenPassword_whenHashingUsingCommons_thenVerifying() { String hash = "35454B055CC325EA1AF2126E27707052"; String password = "ILoveJava"; - String md5Hex = DigestUtils - .md5Hex(password).toUpperCase(); - + String md5Hex = DigestUtils.md5Hex(password).toUpperCase(); + assertThat(md5Hex.equals(hash)).isTrue(); } - - + @Test public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { String filename = "src/test/resources/test_md5.txt"; String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - HashCode hash = com.google.common.io.Files - .hash(new File(filename), Hashing.md5()); - String myChecksum = hash.toString() - .toUpperCase(); - + + HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString().toUpperCase(); + assertThat(myChecksum.equals(checksum)).isTrue(); } - } diff --git a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java similarity index 98% rename from core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java rename to core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java index 5127ccb10c..bb849d6a13 100644 --- a/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaTest.java +++ b/core-java/src/test/java/org/baeldung/java/sandbox/SandboxJavaManualTest.java @@ -6,7 +6,7 @@ import java.util.TimerTask; import org.junit.Test; -public class SandboxJavaTest { +public class SandboxJavaManualTest { @Test public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { diff --git a/couchbase-sdk/pom.xml b/couchbase-sdk/pom.xml index 4c277f4c85..b7b3d1788f 100644 --- a/couchbase-sdk/pom.xml +++ b/couchbase-sdk/pom.xml @@ -85,6 +85,17 @@ 1.7 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + @@ -97,6 +108,7 @@ 1.7.12 4.11 3.4 + 2.19.1 diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java similarity index 98% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java index afc5bbd53b..5907a4cc63 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java @@ -21,7 +21,7 @@ import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceTest extends AsyncIntegrationTest { +public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java similarity index 94% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java index 8ecb51a4b9..08e3728c77 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java @@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends AsyncIntegrationTest { +public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java similarity index 97% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java index 601b261f6e..b3fadae6ca 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.baeldung.couchbase.spring.IntegrationTest; -public class PersonCrudServiceTest extends IntegrationTest { +public class PersonCrudServiceIntegrationTest extends IntegrationTest { private static final String CLARK_KENT = "Clark Kent"; private static final String SMALLVILLE = "Smallville"; diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java similarity index 94% rename from couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java index d1968e1c04..f3ee4585a3 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java @@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends IntegrationTest { +public class ClusterServiceIntegrationTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java new file mode 100644 index 0000000000..d24c0a94b3 --- /dev/null +++ b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/AuditFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.enterprise.patterns.front.controller.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class AuditFilter extends BaseFilter { + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpSession session = httpServletRequest.getSession(false); + if (session != null && session.getAttribute("username") != null) { + request.setAttribute("username", session.getAttribute("username")); + } + chain.doFilter(request, response); + } +} diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java new file mode 100644 index 0000000000..0ae7cd73fd --- /dev/null +++ b/enterprise-patterns/intercepting-filter-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/filters/VisitorCounterFilter.java @@ -0,0 +1,23 @@ +package com.baeldung.enterprise.patterns.front.controller.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; + +@WebFilter(servletNames = "front-controller") +public class VisitorCounterFilter extends BaseFilter { + private int counter; + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + request.setAttribute("counter", ++counter); + chain.doFilter(request, response); + } +} diff --git a/feign-client/README.md b/feign/README.md similarity index 100% rename from feign-client/README.md rename to feign/README.md diff --git a/feign-client/pom.xml b/feign/pom.xml similarity index 100% rename from feign-client/pom.xml rename to feign/pom.xml diff --git a/feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java rename to feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java diff --git a/feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java b/feign/src/main/java/com/baeldung/feign/clients/BookClient.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/clients/BookClient.java rename to feign/src/main/java/com/baeldung/feign/clients/BookClient.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/Book.java b/feign/src/main/java/com/baeldung/feign/models/Book.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/Book.java rename to feign/src/main/java/com/baeldung/feign/models/Book.java diff --git a/feign-client/src/main/java/com/baeldung/feign/models/BookResource.java b/feign/src/main/java/com/baeldung/feign/models/BookResource.java similarity index 100% rename from feign-client/src/main/java/com/baeldung/feign/models/BookResource.java rename to feign/src/main/java/com/baeldung/feign/models/BookResource.java diff --git a/feign-client/src/main/resources/log4j2.xml b/feign/src/main/resources/log4j2.xml similarity index 100% rename from feign-client/src/main/resources/log4j2.xml rename to feign/src/main/resources/log4j2.xml diff --git a/feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java similarity index 100% rename from feign-client/src/test/java/com/baeldung/feign/clients/BookClientTest.java rename to feign/src/test/java/com/baeldung/feign/clients/BookClientTest.java diff --git a/flyway-migration/.gitignore b/flyway/.gitignore similarity index 75% rename from flyway-migration/.gitignore rename to flyway/.gitignore index abffe04ed2..9cdd5b9542 100644 --- a/flyway-migration/.gitignore +++ b/flyway/.gitignore @@ -1,4 +1,4 @@ -.classpath -.project -.settings +.classpath +.project +.settings target/ \ No newline at end of file diff --git a/flyway-migration/README.MD b/flyway/README.MD similarity index 100% rename from flyway-migration/README.MD rename to flyway/README.MD diff --git a/flyway-migration/db/migration/V1_0__create_employee_schema.sql b/flyway/db/migration/V1_0__create_employee_schema.sql similarity index 77% 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 70% 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 69% 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 90% rename from flyway-migration/pom.xml rename to flyway/pom.xml index 6e9d683a0e..d53bc7dc41 100644 --- a/flyway-migration/pom.xml +++ b/flyway/pom.xml @@ -1,34 +1,34 @@ - - 4.0.0 - com.baeldung - flyway-migration - 1.0 - flyway-migration - A sample project to demonstrate Flyway migrations - - - mysql - mysql-connector-java - 6.0.3 - - - - - - org.flywaydb - flyway-maven-plugin - 4.0.3 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - + + 4.0.0 + com.baeldung + flyway + 1.0 + flyway + A sample project to demonstrate Flyway migrations + + + mysql + mysql-connector-java + 6.0.3 + + + + + + org.flywaydb + flyway-maven-plugin + 4.0.3 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + \ No newline at end of file diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md deleted file mode 100644 index e662219718..0000000000 --- a/gson-jackson-performance/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Performance of Gson and Jackson - -Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity. - -###Relevant Articles: -- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance) diff --git a/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java index 5bbf776705..92468683bf 100644 --- a/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java +++ b/gson/src/main/java/org/baeldung/gson/entities/ActorGson.java @@ -1,7 +1,10 @@ package org.baeldung.gson.entities; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.TimeZone; public class ActorGson { @@ -18,7 +21,7 @@ public class ActorGson { @Override public String toString() { - return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; } public String getImdbId() { @@ -45,5 +48,10 @@ public class ActorGson { this.filmography = filmography; } + private String formatDateOfBirth() { + final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); + formatter.setTimeZone(TimeZone.getTimeZone("GMT")); + return formatter.format(dateOfBirth); + } } \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java index 70a03500d5..016e3ba1e2 100644 --- a/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java +++ b/gson/src/main/java/org/baeldung/gson/serialization/ActorGsonDeserializer.java @@ -1,27 +1,33 @@ package org.baeldung.gson.serialization; -import com.google.gson.*; -import org.baeldung.gson.entities.ActorGson; - import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; +import org.baeldung.gson.entities.ActorGson; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + public class ActorGsonDeserializer implements JsonDeserializer { - private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); @Override public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { - JsonObject jsonObject = json.getAsJsonObject(); + final JsonObject jsonObject = json.getAsJsonObject(); - JsonElement jsonImdbId = jsonObject.get("imdbId"); - JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); - JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); + final JsonElement jsonImdbId = jsonObject.get("imdbId"); + final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); + final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); - ArrayList filmList = new ArrayList(); + final ArrayList filmList = new ArrayList(); if (jsonFilmography != null) { for (int i = 0; i < jsonFilmography.size(); i++) { filmList.add(jsonFilmography.get(i).getAsString()); @@ -31,7 +37,7 @@ public class ActorGsonDeserializer implements JsonDeserializer { ActorGson actorGson = null; try { actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList); - } catch (ParseException e) { + } catch (final ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java index d87f0f4bd9..3844c55cd8 100644 --- a/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java +++ b/gson/src/test/java/org/baeldung/gson/deserialization/GsonDeserializeTest.java @@ -1,38 +1,40 @@ package org.baeldung.gson.deserialization; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.text.ParseException; + import org.baeldung.gson.entities.ActorGson; import org.baeldung.gson.entities.Movie; import org.baeldung.gson.serialization.ActorGsonDeserializer; import org.junit.Assert; import org.junit.Test; -import java.text.ParseException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; public class GsonDeserializeTest { - @Test public void whenSimpleDeserialize_thenCorrect() throws ParseException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Tue Sep 21 11:00:00 GMT 1982\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Movie outputMovie = new Gson().fromJson(jsonInput, Movie.class); + final Gson gson = new GsonBuilder().setDateFormat("EEE MMM dd hh:mm:ss zzz yyyy").create(); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final Movie outputMovie = gson.fromJson(jsonInput, Movie.class); + + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(outputMovie.toString(), expectedOutput); } @Test public void whenCustomDeserialize_thenCorrect() throws ParseException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create(); + final Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create(); - Movie outputMovie = gson.fromJson(jsonInput, Movie.class); + final Movie outputMovie = gson.fromJson(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(outputMovie.toString(), expectedOutput); } } diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 66b2076852..cac363c414 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -141,12 +141,52 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + + + + 4.3.11.Final diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index bfe1e68ebe..b1399dcab8 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -51,7 +51,7 @@ public class HttpAsyncClientLiveTest { @Test public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException { final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault(); - // client.start(); + client.start(); final HttpGet request = new HttpGet(HOST); final Future future = client.execute(request, null); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java similarity index 98% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 371657af62..6fad126537 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -28,15 +28,17 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; -public class HttpClientMultipartTest { +@Ignore("Server is not available") +public class HttpClientMultipartLiveTest { private static final String SERVER = "http://echo.200please.com"; private static final String TEXTFILENAME = "temp.txt"; private static final String IMAGEFILENAME = "image.jpg"; private static final String ZIPFILENAME = "zipFile.zip"; - private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartTest"); + private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartLiveTest"); private CloseableHttpClient client; private HttpPost post; private BufferedReader rd; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java similarity index 98% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index 7b75cdfc19..23cbfde82d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -27,9 +27,11 @@ import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; +import org.junit.Ignore; import org.junit.Test; -public class HttpClientPostingTest { +@Ignore("need spring-rest module running") +public class HttpClientPostingLiveTest { private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 952ce3af25..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/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 23c1fdf430..878d220f67 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -1,16 +1,8 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -23,6 +15,13 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + public class HttpClientLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -56,7 +55,7 @@ public class HttpClientLiveTest { // tests @Test(expected = ConnectTimeoutException.class) - public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException { + public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); @@ -66,20 +65,20 @@ public class HttpClientLiveTest { // tests - configs @Test - public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException { instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build(); response = instance.execute(new HttpGet(SAMPLE_URL)); } @Test - public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, "application/xml"); response = instance.execute(request); } @Test - public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws ClientProtocolException, IOException { + public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException { response = instance.execute(new HttpGet(SAMPLE_URL)); final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); @@ -89,7 +88,7 @@ public class HttpClientLiveTest { // tests - cancel request @Test - public final void whenRequestIsCanceled_thenCorrect() throws ClientProtocolException, IOException { + public final void whenRequestIsCanceled_thenCorrect() throws IOException { instance = HttpClients.custom().build(); final HttpGet request = new HttpGet(SAMPLE_URL); response = instance.execute(request); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index 2333e2f8c9..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,34 +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.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.junit.After; import org.junit.Test; +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(); @@ -41,33 +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()); - } - - @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - - final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002"); - httpGet.setHeader("Accept", "application/xml"); - - response = httpClient.execute(httpGet); - } - } diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 42828e1c97..54c17f1487 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -112,9 +112,54 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java index 68cd6117d6..375b2204ff 100644 --- a/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java +++ b/jackson/src/main/java/org/baeldung/jackson/entities/ActorJackson.java @@ -1,7 +1,10 @@ package org.baeldung.jackson.entities; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; +import java.util.TimeZone; public class ActorJackson { @@ -22,7 +25,7 @@ public class ActorJackson { @Override public String toString() { - return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]"; + return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; } public String getImdbId() { @@ -49,4 +52,9 @@ public class ActorJackson { this.filmography = filmography; } + private String formatDateOfBirth() { + final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); + formatter.setTimeZone(TimeZone.getTimeZone("GMT")); + return formatter.format(dateOfBirth); + } } diff --git a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java index 71d5ad3d81..503b6eb99b 100644 --- a/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/deserialization/JacksonDeserializeTest.java @@ -1,39 +1,40 @@ package org.baeldung.jackson.deserialization; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.baeldung.jackson.entities.Movie; -import org.junit.Assert; -import org.junit.Test; - import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; +import org.baeldung.jackson.entities.Movie; +import org.junit.Assert; +import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; + public class JacksonDeserializeTest { @Test public void whenSimpleDeserialize_thenCorrect() throws IOException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - ObjectMapper mapper = new ObjectMapper(); - Movie movie = mapper.readValue(jsonInput, Movie.class); + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final ObjectMapper mapper = new ObjectMapper(); + final Movie movie = mapper.readValue(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(movie.toString(), expectedOutput); } @Test public void whenCustomDeserialize_thenCorrect() throws IOException { - String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - ObjectMapper mapper = new ObjectMapper(); - final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + final ObjectMapper mapper = new ObjectMapper(); + final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); mapper.setDateFormat(df); - Movie movie = mapper.readValue(jsonInput, Movie.class); + final Movie movie = mapper.readValue(jsonInput, Movie.class); - String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; + final String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; Assert.assertEquals(movie.toString(), expectedOutput); } diff --git a/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java index 6c8aa90fae..6d9e378025 100644 --- a/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/serialization/JacksonSerializeTest.java @@ -1,22 +1,19 @@ package org.baeldung.jackson.serialization; import java.io.IOException; -import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.TimeZone; import org.baeldung.jackson.entities.ActorJackson; import org.baeldung.jackson.entities.Movie; import org.baeldung.jackson.entities.MovieWithNullValue; -import org.baeldung.jackson.serialization.ActorJacksonSerializer; import org.junit.Assert; import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -26,34 +23,35 @@ public class JacksonSerializeTest { @Test public void whenSimpleSerialize_thenCorrect() throws JsonProcessingException, ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); + final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + final Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); - ObjectMapper mapper = new ObjectMapper(); - String jsonResult = mapper.writeValueAsString(movie); + final ObjectMapper mapper = new ObjectMapper(); + final String jsonResult = mapper.writeValueAsString(movie); - String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401439600000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + final String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401414400000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; Assert.assertEquals(jsonResult, expectedOutput); } @Test public void whenCustomSerialize_thenCorrect() throws ParseException, IOException { - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); + final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); + final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); - SimpleModule module = new SimpleModule(); + final SimpleModule module = new SimpleModule(); module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); - ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); - String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); - Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); + final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); Assert.assertEquals(jsonResult, expectedOutput); } diff --git a/java-cassandra/pom.xml b/java-cassandra/pom.xml index a91c3b9b62..92d3a8ede6 100644 --- a/java-cassandra/pom.xml +++ b/java-cassandra/pom.xml @@ -76,8 +76,54 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + UTF-8 @@ -97,6 +143,7 @@ 3.5.1 + 2.19.1 3.1.0 diff --git a/jee7schedule/README.md b/jee7/README.md similarity index 100% rename from jee7schedule/README.md rename to jee7/README.md diff --git a/jee7schedule/pom.xml b/jee7/pom.xml similarity index 100% rename from jee7schedule/pom.xml rename to jee7/pom.xml diff --git a/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java rename to jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java b/jee7/src/main/java/com/baeldung/timer/TimerEvent.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java rename to jee7/src/main/java/com/baeldung/timer/TimerEvent.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee7/src/main/java/com/baeldung/timer/TimerEventListener.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java rename to jee7/src/main/java/com/baeldung/timer/TimerEventListener.java diff --git a/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java b/jee7/src/main/java/com/baeldung/timer/WorkerBean.java similarity index 100% rename from jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java rename to jee7/src/main/java/com/baeldung/timer/WorkerBean.java diff --git a/jee7schedule/src/main/webapp/WEB-INF/beans.xml b/jee7/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jee7schedule/src/main/webapp/WEB-INF/beans.xml rename to jee7/src/main/webapp/WEB-INF/beans.xml diff --git a/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java b/jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java rename to jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java diff --git a/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java similarity index 100% rename from jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java rename to jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 24f1c5c5ab..d2a3f1cdd8 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -58,8 +58,51 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + - - - + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java similarity index 91% rename from jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java rename to jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java index 82138ea23e..df147232d9 100644 --- a/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationTests.java +++ b/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/DemoApplicationIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JJWTFunApplication.class) @WebAppConfiguration -public class DemoApplicationTests { +public class DemoApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/jpa-storedprocedure/pom.xml b/jpa-storedprocedure/pom.xml index b2ebaa32e2..b5a2e8693c 100644 --- a/jpa-storedprocedure/pom.xml +++ b/jpa-storedprocedure/pom.xml @@ -11,6 +11,7 @@ 7.0 5.1.0.Final 5.1.38 + 2.19.1 @@ -33,6 +34,16 @@ + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + + + diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index 69351d9683..c93d59fe30 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureTest { +public class StoredProcedureIntegrationTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml new file mode 100644 index 0000000000..2dabf484e1 --- /dev/null +++ b/patterns/front-controller/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + front-controller + war + + + patterns-parent + com.baeldung.patterns + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + + + org.eclipse.jetty + jetty-maven-plugin + + + /front-controller + + + + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java similarity index 76% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java index a8962f5108..9fb120399c 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/FrontControllerServlet.java @@ -1,7 +1,7 @@ -package com.baeldung.enterprise.patterns.front.controller; +package com.baeldung.patterns.front.controller; -import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand; -import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand; +import com.baeldung.patterns.front.controller.commands.FrontCommand; +import com.baeldung.patterns.front.controller.commands.UnknownCommand; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -24,7 +24,7 @@ public class FrontControllerServlet extends HttpServlet { try { Class type = Class.forName( String.format( - "com.baeldung.enterprise.patterns.front.controller.commands.%sCommand", + "com.baeldung.patterns.front.controller.commands.%sCommand", request.getParameter("command") ) ); diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java similarity index 93% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java index 12a008faeb..cc92731050 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/FrontCommand.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java similarity index 69% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java index 0c5bd64bbc..21028b07f0 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/SearchCommand.java @@ -1,7 +1,7 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; -import com.baeldung.enterprise.patterns.front.controller.data.Book; -import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl; +import com.baeldung.patterns.front.controller.data.Book; +import com.baeldung.patterns.front.controller.data.BookshelfImpl; import javax.servlet.ServletException; import java.io.IOException; diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java similarity index 77% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java index 90103c8f42..9f24746598 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/commands/UnknownCommand.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.commands; +package com.baeldung.patterns.front.controller.commands; import javax.servlet.ServletException; import java.io.IOException; diff --git a/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java new file mode 100644 index 0000000000..5a15df92c4 --- /dev/null +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Book.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.front.controller.data; + +public interface Book { + String getAuthor(); + + void setAuthor(String author); + + String getTitle(); + + void setTitle(String title); + + Double getPrice(); + + void setPrice(Double price); +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java similarity index 69% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java index 634e05c3a0..0421ff5623 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookImpl.java @@ -1,39 +1,45 @@ -package com.baeldung.enterprise.patterns.front.controller.data; +package com.baeldung.patterns.front.controller.data; -public class Book { +public class BookImpl implements Book { private String author; private String title; private Double price; - public Book() { + public BookImpl() { } - public Book(String author, String title, Double price) { + public BookImpl(String author, String title, Double price) { this.author = author; this.title = title; this.price = price; } + @Override public String getAuthor() { return author; } + @Override public void setAuthor(String author) { this.author = author; } + @Override public String getTitle() { return title; } + @Override public void setTitle(String title) { this.title = title; } + @Override public Double getPrice() { return price; } + @Override public void setPrice(Double price) { this.price = price; } diff --git a/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java new file mode 100644 index 0000000000..21e3067133 --- /dev/null +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/Bookshelf.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.front.controller.data; + +public interface Bookshelf { + + default void init() { + add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + } + + Bookshelf getInstance(); + + boolean add(E book); + + Book findByTitle(String title); +} diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java similarity index 89% rename from patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java rename to patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java index 3862418857..dd1fa4e523 100644 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java +++ b/patterns/front-controller/src/main/java/com/baeldung/patterns/front/controller/data/BookshelfImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.enterprise.patterns.front.controller.data; +package com.baeldung.patterns.front.controller.data; import java.util.ArrayList; diff --git a/patterns/front-controller/src/main/resources/front controller.png b/patterns/front-controller/src/main/resources/front controller.png new file mode 100644 index 0000000000..bd475bf3f3 Binary files /dev/null and b/patterns/front-controller/src/main/resources/front controller.png differ diff --git a/patterns/front-controller/src/main/resources/front controller.puml b/patterns/front-controller/src/main/resources/front controller.puml new file mode 100644 index 0000000000..fbd4f416ef --- /dev/null +++ b/patterns/front-controller/src/main/resources/front controller.puml @@ -0,0 +1,22 @@ +@startuml + +class Handler { +doGet +doPost +} + +abstract class AbstractCommand { +process +} +class ConcreteCommand1 { +process +} +class ConcreteCommand2 { +process +} + +Handler .right.> AbstractCommand +AbstractCommand <|-- ConcreteCommand1 +AbstractCommand <|-- ConcreteCommand2 + +@enduml \ No newline at end of file diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-found.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-found.jsp diff --git a/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-notfound.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/book-notfound.jsp diff --git a/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/front-controller/src/main/webapp/WEB-INF/jsp/unknown.jsp similarity index 100% rename from patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp rename to patterns/front-controller/src/main/webapp/WEB-INF/jsp/unknown.jsp diff --git a/patterns/src/main/webapp/WEB-INF/web.xml b/patterns/front-controller/src/main/webapp/WEB-INF/web.xml similarity index 82% rename from patterns/src/main/webapp/WEB-INF/web.xml rename to patterns/front-controller/src/main/webapp/WEB-INF/web.xml index 77113db09b..4abca2bb97 100644 --- a/patterns/src/main/webapp/WEB-INF/web.xml +++ b/patterns/front-controller/src/main/webapp/WEB-INF/web.xml @@ -6,7 +6,7 @@ version="3.1"> front-controller - com.baeldung.enterprise.patterns.front.controller.FrontControllerServlet + com.baeldung.patterns.front.controller.FrontControllerServlet front-controller diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml new file mode 100644 index 0000000000..2cf89246f9 --- /dev/null +++ b/patterns/intercepting-filter/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + intercepting-filter + war + + + com.baeldung.patterns + patterns-parent + 1.0.0-SNAPSHOT + .. + + + + + javax.servlet + javax.servlet-api + + + org.slf4j + slf4j-api + 1.7.21 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + org.eclipse.jetty + jetty-maven-plugin + + + / + + + + + + diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java new file mode 100644 index 0000000000..9d8a004265 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/FrontControllerServlet.java @@ -0,0 +1,66 @@ +package com.baeldung.patterns.intercepting.filter; + +import com.baeldung.patterns.intercepting.filter.commands.FrontCommand; +import com.baeldung.patterns.intercepting.filter.commands.UnknownCommand; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; +import com.baeldung.patterns.intercepting.filter.data.BookshelfImpl; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "intercepting-filter", urlPatterns = "/") +public class FrontControllerServlet extends HttpServlet { + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + Bookshelf bookshelf = new BookshelfImpl(); + bookshelf.init(); + getServletContext().setAttribute("bookshelf", bookshelf); + } + + @Override + protected void doGet( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + doCommand(request, response); + } + + @Override + protected void doPost( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + doCommand(request, response); + } + + private void doCommand( + HttpServletRequest request, + HttpServletResponse response + ) throws ServletException, IOException { + FrontCommand command = getCommand(request); + command.init(request, response); + command.process(); + } + + private FrontCommand getCommand(HttpServletRequest request) { + try { + Class type = Class.forName( + String.format( + "com.baeldung.patterns.intercepting.filter.commands.%sCommand", + request.getParameter("command") + ) + ); + return (FrontCommand) type + .asSubclass(FrontCommand.class) + .newInstance(); + } catch (Exception e) { + return new UnknownCommand(); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java new file mode 100644 index 0000000000..fda88c741e --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/CheckoutCommand.java @@ -0,0 +1,27 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Order; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class CheckoutCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + HttpSession session = request.getSession(false); + if (request.getMethod().equals("POST")) { + session.removeAttribute("order"); + response.sendRedirect("/?command=Home&message=Thank you for buying!"); + } else { + Order order = (Order) session.getAttribute("order"); + Double total = order.getItems().entrySet().stream() + .map(entry -> entry.getKey().getPrice() * entry.getValue()) + .reduce((p1, p2) -> p1 + p2) + .orElse(0.00); + request.setAttribute("total", total); + forward("shopping-cart"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java new file mode 100644 index 0000000000..a3c545703b --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/FrontCommand.java @@ -0,0 +1,43 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.filters.FilterManager; +import com.baeldung.patterns.intercepting.filter.filters.OnIntercept; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class FrontCommand implements OnIntercept { + protected HttpServletRequest request; + protected HttpServletResponse response; + private boolean intercept; + + public FrontCommand() { + } + + public void init(HttpServletRequest request, HttpServletResponse response) { + this.request = request; + this.response = response; + } + + public void process() throws ServletException, IOException { + FilterManager.process(request, response, this); + } + + public void forward(String target) throws ServletException, IOException { + if (intercept) { + return; + } + String path = String.format("/WEB-INF/jsp/%s.jsp", target); + RequestDispatcher dispatcher = request.getServletContext() + .getRequestDispatcher(path); + dispatcher.forward(request, response); + } + + @Override + public void intercept() { + intercept = true; + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java new file mode 100644 index 0000000000..33e60b44b5 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/HomeCommand.java @@ -0,0 +1,17 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class HomeCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + request.setAttribute("books", bookshelf); + forward("home"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java new file mode 100644 index 0000000000..cbc8ad9498 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LoginCommand.java @@ -0,0 +1,24 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class LoginCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + if (request.getMethod().equals("POST")) { + HttpSession session = request.getSession(true); + session.setAttribute("username", request.getParameter("username")); + response.sendRedirect(request.getParameter("redirect")); + } else { + String queryString = request.getQueryString(); + if (queryString == null) { + queryString = "command=Home"; + } + request.setAttribute("redirect", request.getRequestURL() + .append("?").append(queryString).toString()); + forward("login"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java new file mode 100644 index 0000000000..3c9475d6af --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/LogoutCommand.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class LogoutCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + HttpSession session = request.getSession(false); + session.removeAttribute("username"); + session.removeAttribute("order"); + response.sendRedirect("/?command=Home"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java new file mode 100644 index 0000000000..e53fcf78dd --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/OrderCommand.java @@ -0,0 +1,33 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; +import com.baeldung.patterns.intercepting.filter.data.Order; +import com.baeldung.patterns.intercepting.filter.data.OrderImpl; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class OrderCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + if (request.getMethod().equals("POST")) { + HttpSession session = request.getSession(false); + Order order = (Order) session.getAttribute("order"); + if (order == null) { + String username = (String) session.getAttribute("username"); + order = new OrderImpl(username); + } + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String isbn = request.getParameter("isbn"); + Integer quantity = Integer.parseInt(request.getParameter("quantity")); + Book book = bookshelf.get(isbn); + order.add(book, quantity); + session.setAttribute("order", order); + response.sendRedirect(String.format("/?command=Show&isbn=%s", isbn)); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java new file mode 100644 index 0000000000..6c52f4f5a9 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/SearchCommand.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.List; + +public class SearchCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String q = request.getParameter("q"); + List books = bookshelf.find(q); + if (books.size() > 0) { + request.setAttribute("books", books); + forward("book-found"); + } else { + forward("book-notfound"); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java new file mode 100644 index 0000000000..1ea5ca6edb --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/ShowCommand.java @@ -0,0 +1,21 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import com.baeldung.patterns.intercepting.filter.data.Book; +import com.baeldung.patterns.intercepting.filter.data.Bookshelf; + +import javax.servlet.ServletException; +import java.io.IOException; +import java.util.Collections; + +public class ShowCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + Bookshelf bookshelf = (Bookshelf) request.getServletContext() + .getAttribute("bookshelf"); + String title = request.getParameter("isbn"); + Book book = bookshelf.get(title); + request.setAttribute("books", Collections.singletonList(book)); + forward("book-found"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java new file mode 100644 index 0000000000..427efe5aba --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/commands/UnknownCommand.java @@ -0,0 +1,12 @@ +package com.baeldung.patterns.intercepting.filter.commands; + +import javax.servlet.ServletException; +import java.io.IOException; + +public class UnknownCommand extends FrontCommand { + @Override + public void process() throws ServletException, IOException { + super.process(); + forward("unknown"); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java new file mode 100644 index 0000000000..4e98095c2c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Book.java @@ -0,0 +1,19 @@ +package com.baeldung.patterns.intercepting.filter.data; + +public interface Book { + String getIsbn(); + + void setIsbn(String isbn); + + String getAuthor(); + + void setAuthor(String author); + + String getTitle(); + + void setTitle(String title); + + Double getPrice(); + + void setPrice(Double price); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java new file mode 100644 index 0000000000..cd0c0924e2 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookImpl.java @@ -0,0 +1,58 @@ +package com.baeldung.patterns.intercepting.filter.data; + +public class BookImpl implements Book { + private String isbn; + private String author; + private String title; + private Double price; + + public BookImpl() { + } + + public BookImpl(String isbn, String author, String title, Double price) { + this.isbn = isbn; + this.author = author; + this.title = title; + this.price = price; + } + + @Override + public String getIsbn() { + return isbn; + } + + @Override + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + @Override + public String getAuthor() { + return author; + } + + @Override + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String getTitle() { + return title; + } + + @Override + public void setTitle(String title) { + this.title = title; + } + + @Override + public Double getPrice() { + return price; + } + + @Override + public void setPrice(Double price) { + this.price = price; + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java new file mode 100644 index 0000000000..26541de8e0 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Bookshelf.java @@ -0,0 +1,18 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.List; + +public interface Bookshelf { + + default void init() { + add(new BookImpl("001", "Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new BookImpl("002", "Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + add(new BookImpl("003", "Unknown", "Something about German Umlauts (äüö) and ß", 5.49)); + } + + boolean add(E book); + + Book get(String isbn); + + List find(String q); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java new file mode 100644 index 0000000000..5767af8e50 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/BookshelfImpl.java @@ -0,0 +1,23 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class BookshelfImpl extends ArrayList implements Bookshelf { + @Override + public Book get(String isbn) { + return this.stream() + .filter(book -> book.getIsbn().equals(isbn)) + .findFirst() + .orElse(null); + } + + @Override + public List find(String q) { + return this.stream() + .filter(book -> book.getTitle().toLowerCase().contains(q.toLowerCase()) + || book.getAuthor().toLowerCase().contains(q.toLowerCase())) + .collect(Collectors.toList()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java new file mode 100644 index 0000000000..f4a32002d7 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/Order.java @@ -0,0 +1,11 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.Map; + +public interface Order { + String getUsername(); + + Map getItems(); + + void add(Book item, Integer quantity); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java new file mode 100644 index 0000000000..9f50e45082 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/data/OrderImpl.java @@ -0,0 +1,40 @@ +package com.baeldung.patterns.intercepting.filter.data; + +import java.util.HashMap; +import java.util.Map; + +public class OrderImpl implements Order { + private String username; + private Map items = new HashMap<>(); + + public OrderImpl(String username) { + this.username = username; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public Map getItems() { + return items; + } + + public void setItems(Map items) { + this.items = items; + } + + @Override + public void add(Book item, Integer quantity) { + Integer q = 0; + if (this.items.containsKey(item)) { + q = this.items.get(item); + } + this.items.put(item, quantity + q); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java new file mode 100644 index 0000000000..a2cac9d84c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/AuthenticationFilter.java @@ -0,0 +1,45 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import com.baeldung.patterns.intercepting.filter.commands.FrontCommand; +import com.baeldung.patterns.intercepting.filter.commands.LoginCommand; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +public class AuthenticationFilter implements Filter { + private OnIntercept callback; + + public AuthenticationFilter(OnIntercept callback) { + this.callback = callback; + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + HttpSession session = httpServletRequest.getSession(false); + if (session == null || session.getAttribute("username") == null) { + callback.intercept(); + FrontCommand command = new LoginCommand(); + command.init(httpServletRequest, httpServletResponse); + command.process(); + } else { + chain.doFilter(request, response); + } + } + + @Override + public void destroy() { + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java new file mode 100644 index 0000000000..90d13a6eda --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/BaseFilter.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.Filter; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; + +public abstract class BaseFilter implements Filter { + private static final Logger log = LoggerFactory.getLogger(BaseFilter.class); + + protected FilterConfig filterConfig; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + log.info("Initialize filter: {}", getClass().getSimpleName()); + this.filterConfig = filterConfig; + } + + @Override + public void destroy() { + log.info("Destroy filter: {}", getClass().getSimpleName()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java new file mode 100644 index 0000000000..ef3f95382e --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/EncodingFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; +import java.io.IOException; + +@WebFilter( + servletNames = {"intercepting-filter"}, + initParams = {@WebInitParam(name = "encoding", value = "UTF-8")} +) +public class EncodingFilter extends BaseFilter { + private String encoding; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + super.init(filterConfig); + this.encoding = filterConfig.getInitParameter("encoding"); + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + String encoding = request.getParameter("encoding"); + if (encoding == null) { + encoding = this.encoding; + } + response.setCharacterEncoding(encoding); + chain.doFilter(request, response); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java new file mode 100644 index 0000000000..80ddef785c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterChainImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; + +public class FilterChainImpl implements FilterChain { + private Iterator filters; + + public FilterChainImpl(Filter... filters) { + this.filters = Arrays.asList(filters).iterator(); + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response + ) throws IOException, ServletException { + if (filters.hasNext()) { + Filter filter = filters.next(); + filter.doFilter(request, response, this); + } + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java new file mode 100644 index 0000000000..2f7b7ac703 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/FilterManager.java @@ -0,0 +1,21 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class FilterManager { + public static void process( + HttpServletRequest request, + HttpServletResponse response, + OnIntercept callback + ) throws ServletException, IOException { + FilterChain filterChain = new FilterChainImpl( + new AuthenticationFilter(callback), + new VisitorCounterFilter() + ); + filterChain.doFilter(request, response); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java new file mode 100644 index 0000000000..0ebb397938 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/LoggingFilter.java @@ -0,0 +1,33 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@WebFilter(servletNames = "intercepting-filter") +public class LoggingFilter extends BaseFilter { + private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class); + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + chain.doFilter(request, response); + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String username = (String) httpServletRequest.getAttribute("username"); + if (username == null) { + username = "guest"; + } + log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(), + httpServletRequest.getRequestURI(), request.getParameterMap()); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java new file mode 100644 index 0000000000..1a138f1e1c --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/OnIntercept.java @@ -0,0 +1,5 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +public interface OnIntercept { + void intercept(); +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java new file mode 100644 index 0000000000..64396ef931 --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/TemplateFilter.java @@ -0,0 +1,34 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class TemplateFilter extends BaseFilter { + protected abstract void preFilter( + HttpServletRequest request, + HttpServletResponse response + ) throws IOException, ServletException; + + protected abstract void postFilter( + HttpServletRequest request, + HttpServletResponse response + ) throws IOException, ServletException; + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + preFilter(httpServletRequest, httpServletResponse); + chain.doFilter(request, response); + postFilter(httpServletRequest, httpServletResponse); + } +} diff --git a/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java new file mode 100644 index 0000000000..5521b9faee --- /dev/null +++ b/patterns/intercepting-filter/src/main/java/com/baeldung/patterns/intercepting/filter/filters/VisitorCounterFilter.java @@ -0,0 +1,33 @@ +package com.baeldung.patterns.intercepting.filter.filters; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +public class VisitorCounterFilter implements Filter { + private static Set users = new HashSet<>(); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + HttpSession session = ((HttpServletRequest) request).getSession(false); + String username = (String) session.getAttribute("username"); + users.add(username); + request.setAttribute("counter", users.size()); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } +} diff --git a/patterns/src/main/resources/front controller.png b/patterns/intercepting-filter/src/main/resources/front_controller.png similarity index 100% rename from patterns/src/main/resources/front controller.png rename to patterns/intercepting-filter/src/main/resources/front_controller.png diff --git a/patterns/src/main/resources/front controller.puml b/patterns/intercepting-filter/src/main/resources/front_controller.puml similarity index 100% rename from patterns/src/main/resources/front controller.puml rename to patterns/intercepting-filter/src/main/resources/front_controller.puml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png new file mode 100644 index 0000000000..2f025fad5e Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml new file mode 100644 index 0000000000..4090085d85 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-custom_strategy.puml @@ -0,0 +1,29 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +class FilterManager { + {static} void process() +} +class FilterChainImpl { + void doFilter() +} +class AuthenticationFilter { + void doFilter() +} +class VisitorCounterFilter { + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet -- FrontCommand +FrontCommand .right.-- FilterManager +FilterManager -- FilterChainImpl +FilterChainImpl .right.-- AuthenticationFilter +AuthenticationFilter .right.-- VisitorCounterFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png new file mode 100644 index 0000000000..0d8db711a7 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml new file mode 100644 index 0000000000..1261d9ee4b --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-standard_strategy.puml @@ -0,0 +1,26 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +abstract class BaseFilter { + void init() + void destroy() +} +class LoggingFilter { + void doFilter() +} +class EncodingFilter { + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet .right.-- FrontCommand +FrontControllerServlet -- BaseFilter +BaseFilter <|-- LoggingFilter +BaseFilter <|-- EncodingFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png new file mode 100644 index 0000000000..5c37aa2937 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml new file mode 100644 index 0000000000..77b001f547 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter-template_strategy.puml @@ -0,0 +1,25 @@ +@startuml +scale 1.5 + +class FrontControllerServlet { + void doGet() + void doPost() +} +abstract class BaseFilter { + void init() + void destroy() +} +abstract class TemplateFilter { + {abstract} void preFilter() + {abstract} void postFilter() + -- + void doFilter() +} +class FrontCommand { + void process() +} + +FrontControllerServlet .right.-- FrontCommand +FrontControllerServlet -- BaseFilter +BaseFilter <|-- TemplateFilter +@enduml diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter.png b/patterns/intercepting-filter/src/main/resources/intercepting_filter.png new file mode 100644 index 0000000000..9ccacc8081 Binary files /dev/null and b/patterns/intercepting-filter/src/main/resources/intercepting_filter.png differ diff --git a/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml b/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml new file mode 100644 index 0000000000..b06b822323 --- /dev/null +++ b/patterns/intercepting-filter/src/main/resources/intercepting_filter.puml @@ -0,0 +1,17 @@ +@startuml +scale 1.5 + +class Client +class FilterManager +interface FilterChain +interface "Filter 1" +interface "Filter 2" +interface "Filter 3" + +Client .right.-- FilterManager +FilterManager .right.-- Target +FilterManager -- FilterChain +FilterChain .right.-- "Filter 3" +FilterChain .right.-- "Filter 2" +FilterChain .right.-- "Filter 1" +@enduml diff --git a/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp new file mode 100644 index 0000000000..4de1d3ca23 --- /dev/null +++ b/patterns/intercepting-filter/src/main/webapp/WEB-INF/jsp/book-found.jsp @@ -0,0 +1,24 @@ +<%@ page import="com.baeldung.patterns.intercepting.filter.data.Book" %> +<%@ page import="java.util.List" %> + + + + Bookshelf: Title found + + +

Our Bookshelf contains following titles:

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

<%= book.getTitle() %>

+

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

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

Our Bookshelf doesn't contains this title:

+

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

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

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

+ <% } else { %> +

Welcome to the Bookshelf!

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

<%= book.getAuthor() %>:

+

<%= book.getTitle() %>

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

Please input a username:

+

Login

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

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

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

You are about to buy the following books:

+

Shopping Cart

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

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

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

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

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

Sorry, this command is not known!

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

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

+<% } %> diff --git a/patterns/pom.xml b/patterns/pom.xml index 7c23b6f55d..6797891353 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -4,46 +4,55 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.enterprise.patterns - patterns - war - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - + com.baeldung.patterns + patterns-parent + pom + + front-controller + intercepting-filter + com.baeldung parent-modules 1.0.0-SNAPSHOT + .. + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - org.eclipse.jetty - jetty-maven-plugin - 9.4.0.M1 - - - /front-controller - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + + org.eclipse.jetty + jetty-maven-plugin + 9.3.12.v20160915 + + + diff --git a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java deleted file mode 100644 index 524e000bd9..0000000000 --- a/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.data; - -public interface Bookshelf { - - default void init() { - add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); - add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); - } - - Bookshelf getInstance(); - - boolean add(E book); - - Book findByTitle(String title); -} diff --git a/play-framework/student-api/.gitignore b/play-framework/introduction/.gitignore similarity index 100% rename from play-framework/student-api/.gitignore rename to play-framework/introduction/.gitignore diff --git a/play-framework/student-api/LICENSE b/play-framework/introduction/LICENSE similarity index 100% rename from play-framework/student-api/LICENSE rename to play-framework/introduction/LICENSE diff --git a/play-framework/student-api/README b/play-framework/introduction/README similarity index 100% rename from play-framework/student-api/README rename to play-framework/introduction/README diff --git a/play-framework/student-api/app/Filters.java b/play-framework/introduction/app/Filters.java similarity index 100% rename from play-framework/student-api/app/Filters.java rename to play-framework/introduction/app/Filters.java diff --git a/play-framework/student-api/app/Module.java b/play-framework/introduction/app/Module.java similarity index 100% rename from play-framework/student-api/app/Module.java rename to play-framework/introduction/app/Module.java diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/introduction/app/controllers/AsyncController.java similarity index 100% rename from play-framework/student-api/app/controllers/AsyncController.java rename to play-framework/introduction/app/controllers/AsyncController.java diff --git a/play-framework/student-api/app/controllers/CountController.java b/play-framework/introduction/app/controllers/CountController.java similarity index 100% rename from play-framework/student-api/app/controllers/CountController.java rename to play-framework/introduction/app/controllers/CountController.java diff --git a/play-framework/student-api/app/controllers/HomeController.java b/play-framework/introduction/app/controllers/HomeController.java similarity index 100% rename from play-framework/student-api/app/controllers/HomeController.java rename to play-framework/introduction/app/controllers/HomeController.java diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/introduction/app/controllers/StudentController.java similarity index 100% rename from play-framework/student-api/app/controllers/StudentController.java rename to play-framework/introduction/app/controllers/StudentController.java diff --git a/play-framework/student-api/app/filters/ExampleFilter.java b/play-framework/introduction/app/filters/ExampleFilter.java similarity index 100% rename from play-framework/student-api/app/filters/ExampleFilter.java rename to play-framework/introduction/app/filters/ExampleFilter.java diff --git a/play-framework/student-api/app/models/Student.java b/play-framework/introduction/app/models/Student.java similarity index 100% rename from play-framework/student-api/app/models/Student.java rename to play-framework/introduction/app/models/Student.java diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/introduction/app/models/StudentStore.java similarity index 100% rename from play-framework/student-api/app/models/StudentStore.java rename to play-framework/introduction/app/models/StudentStore.java diff --git a/play-framework/student-api/app/services/ApplicationTimer.java b/play-framework/introduction/app/services/ApplicationTimer.java similarity index 100% rename from play-framework/student-api/app/services/ApplicationTimer.java rename to play-framework/introduction/app/services/ApplicationTimer.java diff --git a/play-framework/student-api/app/services/AtomicCounter.java b/play-framework/introduction/app/services/AtomicCounter.java similarity index 100% rename from play-framework/student-api/app/services/AtomicCounter.java rename to play-framework/introduction/app/services/AtomicCounter.java diff --git a/play-framework/student-api/app/services/Counter.java b/play-framework/introduction/app/services/Counter.java similarity index 100% rename from play-framework/student-api/app/services/Counter.java rename to play-framework/introduction/app/services/Counter.java diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/introduction/app/util/Util.java similarity index 100% rename from play-framework/student-api/app/util/Util.java rename to play-framework/introduction/app/util/Util.java diff --git a/play-framework/student-api/app/views/index.scala.html b/play-framework/introduction/app/views/index.scala.html similarity index 100% rename from play-framework/student-api/app/views/index.scala.html rename to play-framework/introduction/app/views/index.scala.html diff --git a/play-framework/student-api/app/views/main.scala.html b/play-framework/introduction/app/views/main.scala.html similarity index 100% rename from play-framework/student-api/app/views/main.scala.html rename to play-framework/introduction/app/views/main.scala.html diff --git a/play-framework/student-api/bin/activator b/play-framework/introduction/bin/activator similarity index 100% rename from play-framework/student-api/bin/activator rename to play-framework/introduction/bin/activator diff --git a/play-framework/student-api/bin/activator.bat b/play-framework/introduction/bin/activator.bat similarity index 100% rename from play-framework/student-api/bin/activator.bat rename to play-framework/introduction/bin/activator.bat diff --git a/play-framework/student-api/build.sbt b/play-framework/introduction/build.sbt similarity index 100% rename from play-framework/student-api/build.sbt rename to play-framework/introduction/build.sbt diff --git a/play-framework/student-api/conf/application.conf b/play-framework/introduction/conf/application.conf similarity index 100% rename from play-framework/student-api/conf/application.conf rename to play-framework/introduction/conf/application.conf diff --git a/play-framework/student-api/conf/logback.xml b/play-framework/introduction/conf/logback.xml similarity index 100% rename from play-framework/student-api/conf/logback.xml rename to play-framework/introduction/conf/logback.xml diff --git a/play-framework/student-api/conf/routes b/play-framework/introduction/conf/routes similarity index 100% rename from play-framework/student-api/conf/routes rename to play-framework/introduction/conf/routes diff --git a/play-framework/student-api/libexec/activator-launch-1.3.10.jar b/play-framework/introduction/libexec/activator-launch-1.3.10.jar similarity index 100% rename from play-framework/student-api/libexec/activator-launch-1.3.10.jar rename to play-framework/introduction/libexec/activator-launch-1.3.10.jar diff --git a/play-framework/student-api/project/build.properties b/play-framework/introduction/project/build.properties similarity index 100% rename from play-framework/student-api/project/build.properties rename to play-framework/introduction/project/build.properties diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/introduction/project/plugins.sbt similarity index 100% rename from play-framework/student-api/project/plugins.sbt rename to play-framework/introduction/project/plugins.sbt diff --git a/play-framework/student-api/public/images/favicon.png b/play-framework/introduction/public/images/favicon.png similarity index 100% rename from play-framework/student-api/public/images/favicon.png rename to play-framework/introduction/public/images/favicon.png diff --git a/play-framework/student-api/public/javascripts/hello.js b/play-framework/introduction/public/javascripts/hello.js similarity index 100% rename from play-framework/student-api/public/javascripts/hello.js rename to play-framework/introduction/public/javascripts/hello.js diff --git a/play-framework/student-api/public/stylesheets/main.css b/play-framework/introduction/public/stylesheets/main.css similarity index 100% rename from play-framework/student-api/public/stylesheets/main.css rename to play-framework/introduction/public/stylesheets/main.css diff --git a/play-framework/introduction/test/ApplicationTest.java b/play-framework/introduction/test/ApplicationTest.java new file mode 100644 index 0000000000..1133978e9a --- /dev/null +++ b/play-framework/introduction/test/ApplicationTest.java @@ -0,0 +1,172 @@ + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import model.Student; +import play.test.*; +import static play.test.Helpers.*; + +public class ApplicationTest{ + private static final String BASE_URL = "http://localhost:9000"; + + @Test +public void testInServer() throws Exception { + TestServer server = testServer(3333); + running(server, () -> { + try { + WSClient ws = play.libs.ws.WS.newClient(3333); + CompletionStage completionStage = ws.url("/").get(); + WSResponse response = completionStage.toCompletableFuture().get(); + ws.close(); + assertEquals(OK, response.getStatus()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); +} + @Test + public void whenCreatesRecord_thenCorrect() { + Student student = new Student("jody", "west", 50); + JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); + assertTrue(obj.getBoolean("isSuccessfull")); + JSONObject body = obj.getJSONObject("body"); + assertEquals(student.getAge(), body.getInt("age")); + assertEquals(student.getFirstName(), body.getString("firstName")); + assertEquals(student.getLastName(), body.getString("lastName")); + } + + @Test + public void whenDeletesCreatedRecord_thenCorrect() { + Student student = new Student("Usain", "Bolt", 25); + JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + int id = ob1.getInt("id"); + JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertTrue(obj1.getBoolean("isSuccessfull")); + makeRequest(BASE_URL + "/" + id, "DELETE", null); + JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); + assertFalse(obj2.getBoolean("isSuccessfull")); + } + + @Test + public void whenUpdatesCreatedRecord_thenCorrect() { + Student student = new Student("john", "doe", 50); + JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); + assertEquals(student.getAge(), body1.getInt("age")); + int newAge = 60; + body1.put("age", newAge); + JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); + assertFalse(student.getAge() == body2.getInt("age")); + assertTrue(newAge == body2.getInt("age")); + } + + @Test + public void whenGetsAllRecords_thenCorrect() { + Student student1 = new Student("jane", "daisy", 50); + Student student2 = new Student("john", "daniel", 60); + Student student3 = new Student("don", "mason", 55); + Student student4 = new Student("scarlet", "ohara", 90); + + makeRequest(BASE_URL, "POST", new JSONObject(student1)); + makeRequest(BASE_URL, "POST", new JSONObject(student2)); + makeRequest(BASE_URL, "POST", new JSONObject(student3)); + makeRequest(BASE_URL, "POST", new JSONObject(student4)); + + JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); + assertTrue(objects.getBoolean("isSuccessfull")); + JSONArray array = objects.getJSONArray("body"); + assertTrue(array.length() >= 4); + } + + public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { + + URL url = null; + try { + url = new URL(myUrl); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + HttpURLConnection conn = null; + try { + + conn = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + conn.setDoInput(true); + + conn.setReadTimeout(10000); + + conn.setRequestProperty("Content-Type", "application/json"); + DataOutputStream dos = null; + int respCode = 0; + String inputString = null; + try { + conn.setRequestMethod(httpMethod); + + if (Arrays.asList("POST", "PUT").contains(httpMethod)) { + String params = parameters.toString(); + + conn.setDoOutput(true); + + dos = new DataOutputStream(conn.getOutputStream()); + dos.writeBytes(params); + dos.flush(); + dos.close(); + } + respCode = conn.getResponseCode(); + if (respCode != 200 && respCode != 201) { + String error = inputStreamToString(conn.getErrorStream()); + return error; + } + inputString = inputStreamToString(conn.getInputStream()); + + } catch (IOException e) { + + e.printStackTrace(); + } + return inputString; + } + + public static String inputStreamToString(InputStream is) { + BufferedReader br = null; + StringBuilder sb = new StringBuilder(); + + String line; + try { + + br = new BufferedReader(new InputStreamReader(is)); + while ((line = br.readLine()) != null) { + sb.append(line); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return sb.toString(); + + } +} diff --git a/routing-in-play/.gitignore b/play-framework/routing-in-play/.gitignore similarity index 100% rename from routing-in-play/.gitignore rename to play-framework/routing-in-play/.gitignore diff --git a/routing-in-play/LICENSE b/play-framework/routing-in-play/LICENSE similarity index 100% rename from routing-in-play/LICENSE rename to play-framework/routing-in-play/LICENSE diff --git a/routing-in-play/README b/play-framework/routing-in-play/README similarity index 100% rename from routing-in-play/README rename to play-framework/routing-in-play/README diff --git a/routing-in-play/app/Filters.java b/play-framework/routing-in-play/app/Filters.java similarity index 100% rename from routing-in-play/app/Filters.java rename to play-framework/routing-in-play/app/Filters.java diff --git a/routing-in-play/app/Module.java b/play-framework/routing-in-play/app/Module.java similarity index 100% rename from routing-in-play/app/Module.java rename to play-framework/routing-in-play/app/Module.java diff --git a/routing-in-play/app/controllers/HomeController.java b/play-framework/routing-in-play/app/controllers/HomeController.java similarity index 100% rename from routing-in-play/app/controllers/HomeController.java rename to play-framework/routing-in-play/app/controllers/HomeController.java diff --git a/routing-in-play/app/filters/ExampleFilter.java b/play-framework/routing-in-play/app/filters/ExampleFilter.java similarity index 100% rename from routing-in-play/app/filters/ExampleFilter.java rename to play-framework/routing-in-play/app/filters/ExampleFilter.java diff --git a/routing-in-play/app/services/ApplicationTimer.java b/play-framework/routing-in-play/app/services/ApplicationTimer.java similarity index 100% rename from routing-in-play/app/services/ApplicationTimer.java rename to play-framework/routing-in-play/app/services/ApplicationTimer.java diff --git a/routing-in-play/app/services/AtomicCounter.java b/play-framework/routing-in-play/app/services/AtomicCounter.java similarity index 100% rename from routing-in-play/app/services/AtomicCounter.java rename to play-framework/routing-in-play/app/services/AtomicCounter.java diff --git a/routing-in-play/app/services/Counter.java b/play-framework/routing-in-play/app/services/Counter.java similarity index 100% rename from routing-in-play/app/services/Counter.java rename to play-framework/routing-in-play/app/services/Counter.java diff --git a/routing-in-play/app/views/index.scala.html b/play-framework/routing-in-play/app/views/index.scala.html similarity index 100% rename from routing-in-play/app/views/index.scala.html rename to play-framework/routing-in-play/app/views/index.scala.html diff --git a/routing-in-play/app/views/main.scala.html b/play-framework/routing-in-play/app/views/main.scala.html similarity index 100% rename from routing-in-play/app/views/main.scala.html rename to play-framework/routing-in-play/app/views/main.scala.html diff --git a/routing-in-play/bin/activator b/play-framework/routing-in-play/bin/activator similarity index 100% rename from routing-in-play/bin/activator rename to play-framework/routing-in-play/bin/activator diff --git a/routing-in-play/bin/activator.bat b/play-framework/routing-in-play/bin/activator.bat similarity index 100% rename from routing-in-play/bin/activator.bat rename to play-framework/routing-in-play/bin/activator.bat diff --git a/routing-in-play/build.sbt b/play-framework/routing-in-play/build.sbt similarity index 100% rename from routing-in-play/build.sbt rename to play-framework/routing-in-play/build.sbt diff --git a/routing-in-play/conf/application.conf b/play-framework/routing-in-play/conf/application.conf similarity index 100% rename from routing-in-play/conf/application.conf rename to play-framework/routing-in-play/conf/application.conf diff --git a/routing-in-play/conf/logback.xml b/play-framework/routing-in-play/conf/logback.xml similarity index 100% rename from routing-in-play/conf/logback.xml rename to play-framework/routing-in-play/conf/logback.xml diff --git a/routing-in-play/conf/routes b/play-framework/routing-in-play/conf/routes similarity index 100% rename from routing-in-play/conf/routes rename to play-framework/routing-in-play/conf/routes diff --git a/routing-in-play/libexec/activator-launch-1.3.10.jar b/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar similarity index 100% rename from routing-in-play/libexec/activator-launch-1.3.10.jar rename to play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar diff --git a/routing-in-play/project/build.properties b/play-framework/routing-in-play/project/build.properties similarity index 100% rename from routing-in-play/project/build.properties rename to play-framework/routing-in-play/project/build.properties diff --git a/routing-in-play/project/plugins.sbt b/play-framework/routing-in-play/project/plugins.sbt similarity index 100% rename from routing-in-play/project/plugins.sbt rename to play-framework/routing-in-play/project/plugins.sbt diff --git a/routing-in-play/public/images/favicon.png b/play-framework/routing-in-play/public/images/favicon.png similarity index 100% rename from routing-in-play/public/images/favicon.png rename to play-framework/routing-in-play/public/images/favicon.png diff --git a/routing-in-play/public/javascripts/hello.js b/play-framework/routing-in-play/public/javascripts/hello.js similarity index 100% rename from routing-in-play/public/javascripts/hello.js rename to play-framework/routing-in-play/public/javascripts/hello.js diff --git a/routing-in-play/public/stylesheets/main.css b/play-framework/routing-in-play/public/stylesheets/main.css similarity index 100% rename from routing-in-play/public/stylesheets/main.css rename to play-framework/routing-in-play/public/stylesheets/main.css diff --git a/routing-in-play/test/ApplicationTest.java b/play-framework/routing-in-play/test/ApplicationTest.java similarity index 100% rename from routing-in-play/test/ApplicationTest.java rename to play-framework/routing-in-play/test/ApplicationTest.java diff --git a/routing-in-play/test/IntegrationTest.java b/play-framework/routing-in-play/test/IntegrationTest.java similarity index 100% rename from routing-in-play/test/IntegrationTest.java rename to play-framework/routing-in-play/test/IntegrationTest.java diff --git a/pom.xml b/pom.xml index eee9f07ab9..95182ab63c 100644 --- a/pom.xml +++ b/pom.xml @@ -17,22 +17,22 @@ assertj apache-cxf - autovalue-tutorial + autovalue cdi core-java - core-java-8 couchbase-sdk dozer - dependency-injection deltaspike patterns - feign-client + feign + flyway + gson guava guava18 @@ -46,19 +46,19 @@ jackson javaxval jjwt - jooq-spring + jpa-storedprocedure json json-path junit5 - jee7schedule + jee7 log4j mockito mocks - mutation-testing + testing orika @@ -75,6 +75,7 @@ spring-autowire spring-batch spring-boot + spring-core spring-cucumber spring-data-cassandra spring-data-couchbase-2 @@ -83,12 +84,14 @@ spring-data-mongodb spring-data-redis spring-data-rest + spring-exceptions spring-freemarker spring-hibernate3 spring-hibernate4 - spring-jpa spring-jms + spring-jooq + spring-jpa spring-katharsis spring-mockito spring-mvc-java @@ -125,6 +128,7 @@ jsf xml + xmlunit2 lombok redis diff --git a/resteasy/pom.xml b/resteasy/pom.xml index ec9e87b0d1..04e8576e1f 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -10,6 +10,8 @@ 3.0.14.Final + 2.19.1 + 1.6.0 @@ -23,6 +25,35 @@ 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + @@ -73,5 +104,66 @@ + + + live + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + \ No newline at end of file diff --git a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java similarity index 61% rename from resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java rename to resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java index ef18b0f23f..7e709edb96 100644 --- a/resteasy/src/test/java/com/baeldung/server/RestEasyClientTest.java +++ b/resteasy/src/test/java/com/baeldung/server/RestEasyClientLiveTest.java @@ -1,7 +1,15 @@ package com.baeldung.server; -import com.baeldung.client.ServicesInterface; -import com.baeldung.model.Movie; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +import javax.naming.NamingException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; @@ -14,18 +22,13 @@ import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.junit.Before; import org.junit.Test; -import javax.naming.NamingException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Locale; -public class RestEasyClientTest { +import com.baeldung.client.ServicesInterface; +import com.baeldung.model.Movie; - public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8080/RestEasyTutorial/rest"); +public class RestEasyClientLiveTest { + + public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest"); Movie transformerMovie = null; Movie batmanMovie = null; ObjectMapper jsonMapper = null; @@ -35,22 +38,22 @@ public class RestEasyClientTest { jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); + final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); jsonMapper.setDateFormat(sdf); - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/transformer.json")) { - String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) { + final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); throw new RuntimeException("Test is going to die ...", e); } - try (InputStream inputStream = new RestEasyClientTest().getClass().getResourceAsStream("./movies/batman.json")) { - String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); + try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) { + final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Test is going to die ...", e); } } @@ -58,41 +61,41 @@ public class RestEasyClientTest { @Test public void testListAllMovies() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); - List movies = proxy.listMovies(); + final List movies = proxy.listMovies(); System.out.println(movies); } @Test public void testMovieByImdbId() { - String transformerImdbId = "tt0418279"; + final String transformerImdbId = "tt0418279"; - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response moviesResponse = proxy.addMovie(transformerMovie); + final Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); - Movie movies = proxy.movieByImdbId(transformerImdbId); + final Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); } @Test public void testAddMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -109,17 +112,15 @@ public class RestEasyClientTest { @Test public void testAddMovieMultiConnection() { - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(cm) - .build(); - ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); - ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); + final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); + final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); - Response batmanResponse = proxy.addMovie(batmanMovie); - Response transformerResponse = proxy.addMovie(transformerMovie); + final Response batmanResponse = proxy.addMovie(batmanMovie); + final Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); @@ -132,16 +133,14 @@ public class RestEasyClientTest { transformerResponse.close(); cm.close(); - - } @Test public void testDeleteMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); @@ -159,9 +158,9 @@ public class RestEasyClientTest { @Test public void testUpdateMovie() { - ResteasyClient client = new ResteasyClientBuilder().build(); - ResteasyWebTarget target = client.target(FULL_PATH); - ServicesInterface proxy = target.proxy(ServicesInterface.class); + final ResteasyClient client = new ResteasyClientBuilder().build(); + final ResteasyWebTarget target = client.target(FULL_PATH); + final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index 861c0b1986..cc96ea8529 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -53,7 +53,7 @@ org.seleniumhq.selenium selenium-java - 2.53.1 + 3.0.1 junit 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 1007bf7503..58d47c0162 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -1,6 +1,7 @@ package main.java.com.baeldung.selenium; import java.util.List; +import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; @@ -14,6 +15,7 @@ public class SeleniumExample { private String url = "http://www.baeldung.com/"; public SeleniumExample() { + System.setProperty("webdriver.firefox.marionette", "C:\\selenium\\geckodriver.exe"); webDriver = new FirefoxDriver(); webDriver.manage().window().maximize(); webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); @@ -36,8 +38,12 @@ public class SeleniumExample { 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(); + try { + if (webElementList != null && !webElementList.isEmpty()) { + webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click(); + } + } catch (NoSuchElementException exception) { + exception.printStackTrace(); } } @@ -50,8 +56,6 @@ public class SeleniumExample { } public boolean isAuthorInformationAvailable() { - return webDriver - .findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")) - .isDisplayed(); + return webDriver.findElement(By.xpath("//*[contains(text(), 'Eugen – an engineer')]")).isDisplayed(); } } diff --git a/sockets/README.md b/sockets/README.md deleted file mode 100644 index ad8811ee80..0000000000 --- a/sockets/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) diff --git a/sockets/pom.xml b/sockets/pom.xml deleted file mode 100644 index 24e8e436f3..0000000000 --- a/sockets/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - 4.0.0 - com.baeldung - sockets - 1.0 - sockets - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - - - - junit - junit - 4.3 - test - - - - diff --git a/sockets/src/main/java/com/baeldung/socket/EchoClient.java b/sockets/src/main/java/com/baeldung/socket/EchoClient.java deleted file mode 100644 index e8ec97c80a..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoClient.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.socket; - -import java.io.*; -import java.net.*; - -public class EchoClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - System.out.print(e); - } - - } - - public String sendMessage(String msg) { - try { - out.println(msg); - String resp = in.readLine(); - return resp; - } catch (Exception e) { - return null; - } - } - - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } -} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java b/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java deleted file mode 100644 index 2ece1ceebe..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoMultiServer.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class EchoMultiServer { - private ServerSocket serverSocket; - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - while (true) - new EchoClientHandler(serverSocket.accept()).run(); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - stop(); - } - - } - - public void stop() { - try { - - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - private static class EchoClientHandler extends Thread { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public EchoClientHandler(Socket socket) { - this.clientSocket = socket; - } - - public void run() { - try { - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("bye"); - break; - } - out.println(inputLine); - } - - in.close(); - out.close(); - clientSocket.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public static void main(String[] args) { - EchoMultiServer server = new EchoMultiServer(); - server.start(5555); - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/EchoServer.java b/sockets/src/main/java/com/baeldung/socket/EchoServer.java deleted file mode 100644 index 3607afa7f5..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/EchoServer.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class EchoServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String inputLine; - while ((inputLine = in.readLine()) != null) { - if (".".equals(inputLine)) { - out.println("good bye"); - break; - } - out.println(inputLine); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static void main(String[] args) { - EchoServer server = new EchoServer(); - server.start(4444); - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetClient.java b/sockets/src/main/java/com/baeldung/socket/GreetClient.java deleted file mode 100644 index 7252827c87..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/GreetClient.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.socket; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.Socket; - -public class GreetClient { - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - public void startConnection(String ip, int port) { - try { - clientSocket = new Socket(ip, port); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - } catch (IOException e) { - - } - - } - - public String sendMessage(String msg) { - try { - out.println(msg); - String resp = in.readLine(); - return resp; - } catch (Exception e) { - return null; - } - } - - public void stopConnection() { - try { - in.close(); - out.close(); - clientSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/sockets/src/main/java/com/baeldung/socket/GreetServer.java b/sockets/src/main/java/com/baeldung/socket/GreetServer.java deleted file mode 100644 index 8bf675c7b9..0000000000 --- a/sockets/src/main/java/com/baeldung/socket/GreetServer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.socket; - -import java.net.*; -import java.io.*; - -public class GreetServer { - private ServerSocket serverSocket; - private Socket clientSocket; - private PrintWriter out; - private BufferedReader in; - - - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - clientSocket = serverSocket.accept(); - out = new PrintWriter(clientSocket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader( - clientSocket.getInputStream())); - String greeting = in.readLine(); - if ("hello server".equals(greeting)) - out.println("hello client"); - else - out.println("unrecognised greeting"); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void stop() { - try { - in.close(); - out.close(); - clientSocket.close(); - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - public static void main(String[] args) { - GreetServer server=new GreetServer(); - server.start(6666); - } - -} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java b/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java deleted file mode 100644 index 19a59c211c..0000000000 --- a/sockets/src/test/java/com/baeldung/socket/EchoMultiTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.socket; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - -public class EchoMultiTest { - - { - Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555)); - } - - - @Test - public void givenClient1_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - - @Test - public void givenClient2_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - - @Test - public void givenClient3_whenServerResponds_thenCorrect() { - EchoClient client = new EchoClient(); - client.startConnection("127.0.0.1", 5555); - String msg1 = client.sendMessage("hello"); - String msg2 = client.sendMessage("world"); - String terminate = client.sendMessage("."); - assertEquals(msg1, "hello"); - assertEquals(msg2, "world"); - assertEquals(terminate, "bye"); - client.stopConnection(); - } - -} diff --git a/sockets/src/test/java/com/baeldung/socket/EchoTest.java b/sockets/src/test/java/com/baeldung/socket/EchoTest.java deleted file mode 100644 index 0f0c02e4d8..0000000000 --- a/sockets/src/test/java/com/baeldung/socket/EchoTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.socket; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.concurrent.Executors; - -import static org.junit.Assert.assertEquals; - -public class EchoTest { - { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444)); - } - - EchoClient client = new EchoClient(); - - @Before - public void init() { - client.startConnection("127.0.0.1", 4444); - } - - @Test - public void givenClient_whenServerEchosMessage_thenCorrect() { - - String resp1 = client.sendMessage("hello"); - String resp2 = client.sendMessage("world"); - String resp3 = client.sendMessage("!"); - String resp4 = client.sendMessage("."); - assertEquals("hello", resp1); - assertEquals("world", resp2); - assertEquals("!", resp3); - assertEquals("good bye", resp4); - } - - @After - public void tearDown() { - client.stopConnection(); - } - -} diff --git a/spring-boot-data-dynamodb/.gitignore b/spring-boot-data-dynamodb/.gitignore new file mode 100644 index 0000000000..e26d6af438 --- /dev/null +++ b/spring-boot-data-dynamodb/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project diff --git a/spring-boot-data-dynamodb/README.MD b/spring-boot-data-dynamodb/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-boot-data-dynamodb/README.MD @@ -0,0 +1 @@ + diff --git a/spring-boot-data-dynamodb/pom.xml b/spring-boot-data-dynamodb/pom.xml new file mode 100644 index 0000000000..11e1366f3e --- /dev/null +++ b/spring-boot-data-dynamodb/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + com.baeldung + spring-boot-dynamodb + 0.0.1-SNAPSHOT + jar + Spring Boot Actuator + This is simple boot application for Spring boot actuator test + + + spring-boot-starter-parent + org.springframework.boot + 1.2.3.RELEASE + + + + + + com.baeldung.Application + UTF-8 + 1.8 + 4.3.1.RELEASE + + + + + + org.springframework.data + spring-data-releasetrain + Gosling-SR1 + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-security + + + + io.dropwizard.metrics + metrics-core + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter + + + com.jayway.jsonpath + json-path + test + + + org.springframework.boot + spring-boot-starter-mail + + + + org.webjars + bootstrap + 3.3.4 + + + + com.amazonaws + aws-java-sdk-dynamodb + 1.11.34 + + + com.github.derjust + spring-data-dynamodb + 4.3.1 + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + + + spring-boot + + + src/main/resources + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..f5e0e98fd4 --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung" }) +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java new file mode 100644 index 0000000000..4bc8a128bc --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/config/DynamoDBConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.es.config; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; +import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + +@Configuration +@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.es.repositories") +public class DynamoDBConfig { + + @Value("${amazon.dynamodb.endpoint}") + private String amazonDynamoDBEndpoint; + + @Value("${amazon.aws.accesskey}") + private String amazonAWSAccessKey; + + @Value("${amazon.aws.secretkey}") + private String amazonAWSSecretKey; + + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(amazonAWSCredentials()); + if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) { + amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint); + } + return amazonDynamoDB; + } + + @Bean + public AWSCredentials amazonAWSCredentials() { + return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey); + } + +} diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java new file mode 100644 index 0000000000..3e75c9e6f2 --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/model/ProductInfo.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.data.es.model; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +@DynamoDBTable(tableName = "ProductInfo") +public class ProductInfo { + private String id; + private String msrp; + private String cost; + + public ProductInfo() { + } + + public ProductInfo(String cost, String msrp) { + this.msrp = msrp; + this.cost = cost; + } + + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + public String getId() { + return id; + } + + @DynamoDBAttribute + public String getMsrp() { + return msrp; + } + + @DynamoDBAttribute + public String getCost() { + return cost; + } + + public void setId(String id) { + this.id = id; + } + + public void setMsrp(String msrp) { + this.msrp = msrp; + } + + public void setCost(String cost) { + this.cost = cost; + } +} diff --git a/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java new file mode 100644 index 0000000000..c5eee49634 --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/java/com/baeldung/spring/data/es/repositories/ProductInfoRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.data.es.repositories; + +import com.baeldung.spring.data.es.model.ProductInfo; +import org.socialsignin.spring.data.dynamodb.repository.EnableScan; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +@EnableScan +public interface ProductInfoRepository extends CrudRepository { + List findById(String id); +} diff --git a/spring-boot-data-dynamodb/src/main/resources/application.properties b/spring-boot-data-dynamodb/src/main/resources/application.properties new file mode 100644 index 0000000000..e6911bc9e7 --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/resources/application.properties @@ -0,0 +1,32 @@ +server.port=8080 +server.contextPath=/springbootapp +management.port=8081 +management.address=127.0.0.1 + +endpoints.shutdown.enabled=true + +endpoints.jmx.domain=Spring Sample Application +endpoints.jmx.uniqueNames=true + +spring.jmx.enabled=true +endpoints.jmx.enabled=true + +## for pretty printing of json when endpoints accessed over HTTP +http.mappers.jsonPrettyPrint=true + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 + +## Spring Security Configurations +security.user.name=admin1 +security.user.password=secret1 +management.security.role=SUPERUSER + +logging.level.org.springframework=INFO + +#AWS Keys +amazon.dynamodb.endpoint=http://localhost:8000/ +amazon.aws.accesskey=test1 +amazon.aws.secretkey=test1 \ No newline at end of file diff --git a/spring-boot-data-dynamodb/src/main/resources/demo.properties b/spring-boot-data-dynamodb/src/main/resources/demo.properties new file mode 100644 index 0000000000..649b64f59b --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/resources/demo.properties @@ -0,0 +1,6 @@ +spring.output.ansi.enabled=never +server.port=7070 + +# Security +security.user.name=admin +security.user.password=password \ No newline at end of file diff --git a/spring-boot-data-dynamodb/src/main/resources/logback.xml b/spring-boot-data-dynamodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..c0bc602910 --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + diff --git a/spring-boot-data-dynamodb/src/main/resources/templates/index.html b/spring-boot-data-dynamodb/src/main/resources/templates/index.html new file mode 100644 index 0000000000..046d21600a --- /dev/null +++ b/spring-boot-data-dynamodb/src/main/resources/templates/index.html @@ -0,0 +1,19 @@ + + + WebJars Demo + + + + +

+
+ × + Success! It is working as we expected. +
+
+ + + + + + \ No newline at end of file diff --git a/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java b/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java new file mode 100644 index 0000000000..df727cf727 --- /dev/null +++ b/spring-boot-data-dynamodb/src/test/java/com/baeldung/spring/data/es/repository/ProductInfoRepositoryIntegrationTest.java @@ -0,0 +1,74 @@ +package com.baeldung.spring.data.es.repository; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; +import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; +import com.amazonaws.services.dynamodbv2.model.ResourceInUseException; +import com.baeldung.Application; +import com.baeldung.spring.data.es.model.ProductInfo; +import com.baeldung.spring.data.es.repositories.ProductInfoRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +@IntegrationTest +@ActiveProfiles("local") +@TestPropertySource(properties = { "amazon.dynamodb.endpoint=http://localhost:8000/", "amazon.aws.accesskey=test1", "amazon.aws.secretkey=test231" }) +public class ProductInfoRepositoryIntegrationTest { + + private DynamoDBMapper dynamoDBMapper; + + @Autowired + private AmazonDynamoDB amazonDynamoDB; + + @Autowired + ProductInfoRepository repository; + + private static final String EXPECTED_COST = "20"; + private static final String EXPECTED_PRICE = "50"; + + @Before + public void setup() throws Exception { + + try { + dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB); + + CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(ProductInfo.class); + + tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L)); + + amazonDynamoDB.createTable(tableRequest); + } catch (ResourceInUseException e) { + // Do nothing, table already created + } + + // TODO How to handle different environments. i.e. AVOID deleting all entries in ProductInfoion table + dynamoDBMapper.batchDelete((List) repository.findAll()); + } + + @Test + public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() { + + ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE); + repository.save(productInfo); + + List result = (List) repository.findAll(); + assertTrue("Not empty", result.size() > 0); + assertTrue("Contains item with expected cost", result.get(0).getCost().equals(EXPECTED_COST)); + } +} diff --git a/spring-boot-data-dynamodb/src/test/resources/application.properties b/spring-boot-data-dynamodb/src/test/resources/application.properties new file mode 100644 index 0000000000..01e8a2e52e --- /dev/null +++ b/spring-boot-data-dynamodb/src/test/resources/application.properties @@ -0,0 +1,7 @@ +spring.mail.host=localhost +spring.mail.port=8025 +spring.mail.properties.mail.smtp.auth=false + +amazon.dynamodb.endpoint=http://localhost:8000/ +amazon.aws.accesskey=key +amazon.aws.secretkey=key2 \ No newline at end of file diff --git a/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties b/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties new file mode 100644 index 0000000000..cde746acb9 --- /dev/null +++ b/spring-boot-data-dynamodb/src/test/resources/exception-hibernate.properties @@ -0,0 +1,2 @@ +spring.profiles.active=exception +spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext diff --git a/spring-boot-data-dynamodb/src/test/resources/exception.properties b/spring-boot-data-dynamodb/src/test/resources/exception.properties new file mode 100644 index 0000000000..c55e415a3a --- /dev/null +++ b/spring-boot-data-dynamodb/src/test/resources/exception.properties @@ -0,0 +1,6 @@ +# Security +security.user.name=admin +security.user.password=password + +spring.dao.exceptiontranslation.enabled=false +spring.profiles.active=exception \ No newline at end of file diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 2ddb9d85a3..99e57d4c20 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -67,8 +67,17 @@ org.springframework.boot spring-boot-maven-plugin - - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java similarity index 86% rename from spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java rename to spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java index 5f18ec75c4..f8dfdec197 100644 --- a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationTests.java +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/spring/cloud/BatchJobApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class BatchJobApplicationTests { +public class BatchJobApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index 94c4106d6f..451a58e12a 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -62,8 +62,53 @@ org.springframework.boot spring-boot-maven-plugin - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java new file mode 100644 index 0000000000..bb8660b816 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DataFlowServerApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index a074fef88f..31d3dce507 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -62,8 +62,18 @@ org.springframework.boot spring-boot-maven-plugin - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + diff --git a/spring-cloud-data-flow/data-flow-shell/spring-shell.log b/spring-cloud-data-flow/data-flow-shell/spring-shell.log index d497215e2a..92a8488c7d 100644 --- a/spring-cloud-data-flow/data-flow-shell/spring-shell.log +++ b/spring-cloud-data-flow/data-flow-shell/spring-shell.log @@ -1 +1,2 @@ // dataflow 1.2.0.RELEASE log opened at 2016-10-20 13:13:20 +// dataflow 1.2.0.RELEASE log opened at 2016-10-24 16:51:17 diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java similarity index 85% rename from spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java rename to spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java index 9f88c7f632..5ab3292388 100644 --- a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationTests.java +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class LogSinkApplicationTests { +public class DataFlowShellApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 8415d95373..db488c05ef 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -1,62 +1,105 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.baeldung.spring.cloud - log-sink - 0.0.1-SNAPSHOT - jar + org.baeldung.spring.cloud + log-sink + 0.0.1-SNAPSHOT + jar - log-sink - Demo project for Spring Boot + log-sink + Demo project for Spring Boot - - org.springframework.boot - spring-boot-starter-parent - 1.4.0.RELEASE - - + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + - - - org.springframework.cloud - spring-cloud-starter-stream-rabbit - + + + org.springframework.cloud + spring-cloud-starter-stream-rabbit + - - org.springframework.boot - spring-boot-starter-test - test - - + + org.springframework.boot + spring-boot-starter-test + test + + - - - - org.springframework.cloud - spring-cloud-dependencies - Brixton.SR5 - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.cloud + spring-cloud-dependencies + Brixton.SR5 + pom + import + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java similarity index 86% rename from spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java rename to spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java index f853e29244..b362d72705 100644 --- a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/spring/cloud/DataFlowServerApplicationTests.java +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/spring/cloud/LogSinkApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class DataFlowServerApplicationTests { +public class LogSinkApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index bc2efe7754..8277c9c836 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -49,14 +49,57 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java new file mode 100644 index 0000000000..9bd0fd8c24 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package org.baeldung.spring.cloud; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TimeProcessorApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java deleted file mode 100644 index 875346f9db..0000000000 --- a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/spring/cloud/TimeProcessorApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TimeProcessorApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 587b782227..086d761f78 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -49,14 +49,57 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java similarity index 85% rename from spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java rename to spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java index 7e2bc1cb37..6d71a785a3 100644 --- a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/spring/cloud/DataFlowShellApplicationTests.java +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class DataFlowShellApplicationTests { +public class TimeSourceApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java deleted file mode 100644 index 61fd8323d2..0000000000 --- a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/spring/cloud/TimeSourceApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.spring.cloud; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class TimeSourceApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties index 2131f3b249..9476887a1c 100644 --- a/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-config/server/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8888 -spring.cloud.config.server.git.uri=https://github.com/eugenp/tutorials/tree/master/spring-cloud-config/client-config -spring.cloud.config.server.git.clone-on-start=false +spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo +spring.cloud.config.server.git.clone-on-start=true security.user.name=root security.user.password=s3cr3t encrypt.key-store.location=classpath:/config-server.jks diff --git a/dependency-injection/.gitignore b/spring-core/.gitignore similarity index 100% rename from dependency-injection/.gitignore rename to spring-core/.gitignore diff --git a/dependency-injection/README.md b/spring-core/README.md similarity index 100% rename from dependency-injection/README.md rename to spring-core/README.md diff --git a/dependency-injection/pom.xml b/spring-core/pom.xml similarity index 65% rename from dependency-injection/pom.xml rename to spring-core/pom.xml index 9e78a66ad6..9b94ba7b35 100644 --- a/dependency-injection/pom.xml +++ b/spring-core/pom.xml @@ -66,9 +66,10 @@ org.apache.maven.plugins maven-surefire-plugin - - **/*Test.java - + + **/*IntegrationTest.java + **/*LiveTest.java + @@ -85,6 +86,41 @@ + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + 2.6 diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java b/spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java rename to spring-core/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/ArbitraryDependency.java diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java similarity index 100% rename from dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java rename to spring-core/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java index b736871f85..a78799f1d9 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredType.class) -public class FieldAutowiredTest { +public class FieldAutowiredIntegrationTest { @Autowired private ArbitraryDependency fieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java index cbdac68543..8f09e73c33 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldAutowiredNameIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredName.class) -public class FieldAutowiredNameTest { +public class FieldAutowiredNameIntegrationTest { @Autowired private ArbitraryDependency autowiredFieldDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java b/spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java rename to spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java index cbc3d56f67..01317aef6f 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java +++ b/spring-core/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestAutowiredQualifier.class) -public class FieldQualifierAutowiredTest { +public class FieldQualifierAutowiredIntegrationTest { @Autowired @Qualifier("autowiredFieldDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java index 665c9f1ddc..f5897febab 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldByNameInjectIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectName.class) -public class FieldByNameInjectTest { +public class FieldByNameInjectIntegrationTest { @Inject @Named("yetAnotherFieldInjectDependency") diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java index 7561c39e76..45b7c8015c 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectType.class) -public class FieldInjectTest { +public class FieldInjectIntegrationTest { @Inject private ArbitraryDependency fieldInjectDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java b/spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java rename to spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java index 7e5f7e7453..0fd6a0e4c1 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java +++ b/spring-core/src/test/java/com/baeldung/inject/FieldQualifierInjectIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestInjectQualifier.class) -public class FieldQualifierInjectTest { +public class FieldQualifierInjectIntegrationTest { @Inject @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java similarity index 94% rename from dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java index ef7e7b0aeb..63a25cb499 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/FieldResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class FieldResourceInjectionTest { +public class FieldResourceInjectionIntegrationTest { @Resource(name = "namedFile") private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java similarity index 96% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java index 95e9fc0bd5..f5bb9f10cf 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodByQualifierResourceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class MethodByQualifierResourceTest { +public class MethodByQualifierResourceIntegrationTest { private File arbDependency; private File anotherArbDependency; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java index ad9a9a4fb6..171cbfea47 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodByTypeResourceIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodByTypeResourceTest { +public class MethodByTypeResourceIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java index 1622d8896c..2e1c3c39a9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/MethodResourceInjectionIntegrationTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class MethodResourceInjectionTest { +public class MethodResourceInjectionIntegrationTest { private File defaultFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java rename to spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java index da104ecaae..d52660e9b8 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/NamedResourceIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class NamedResourceTest { +public class NamedResourceIntegrationTest { @Resource(name = "namedFile") private File testFile; diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java index 024c8e2bbe..3f812350c9 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/QualifierResourceInjectionIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceQualifier.class) -public class QualifierResourceInjectionTest { +public class QualifierResourceInjectionIntegrationTest { @Resource @Qualifier("defaultFile") diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java similarity index 95% rename from dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java rename to spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java index aa7cfda975..ae13b2336a 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SetterResourceInjectionIntegrationTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = ApplicationContextTestResourceNameType.class) -public class SetterResourceInjectionTest { +public class SetterResourceInjectionIntegrationTest { private File defaultFile; diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 12b7e5de79..6994a518fe 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -194,7 +194,7 @@ ${maven-surefire-plugin.version} - **/*IntegrationTest.java + **/*ManualTest.java diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java index f88138fec2..9597c09568 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/BeanCreationExceptionTestSuite.java @@ -5,15 +5,15 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - Cause1BeanCreationExceptionIntegrationTest.class - ,Cause2BeanCreationExceptionIntegrationTest.class - ,Cause3BeanCreationExceptionIntegrationTest.class - ,Cause4BeanCreationExceptionIntegrationTest.class - ,Cause5BeanCreationExceptionIntegrationTest.class - ,Cause6BeanCreationExceptionIntegrationTest.class - ,Cause7BeanCreationExceptionIntegrationTest.class - ,Cause8BeanCreationExceptionIntegrationTest.class - ,Cause9BeanCreationExceptionIntegrationTest.class + Cause1BeanCreationExceptionManualTest.class + ,Cause2BeanCreationExceptionManualTest.class + ,Cause3BeanCreationExceptionManualTest.class + ,Cause4BeanCreationExceptionManualTest.class + ,Cause5BeanCreationExceptionManualTest.class + ,Cause6BeanCreationExceptionManualTest.class + ,Cause7BeanCreationExceptionManualTest.class + ,Cause8BeanCreationExceptionManualTest.class + ,Cause9BeanCreationExceptionManualTest.class }) // @formatter:on public class BeanCreationExceptionTestSuite { // diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java index 56d916e25d..350347bb19 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause1BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1BeanCreationExceptionIntegrationTest { +public class Cause1BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java index 968e7312de..c2b9561848 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause2BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2BeanCreationExceptionIntegrationTest { +public class Cause2BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java index 4730d59334..7b9b49bf58 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause3BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3BeanCreationExceptionIntegrationTest { +public class Cause3BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java index b5108c1ab4..3a6e30476c 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause4BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause4BeanCreationExceptionIntegrationTest { +public class Cause4BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java index 9a08ec45a1..e69a323f8d 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause5BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause5BeanCreationExceptionIntegrationTest { +public class Cause5BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java index 423a0a98a9..30fbd47635 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause6BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause6ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause6BeanCreationExceptionIntegrationTest { +public class Cause6BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java index a61e598b41..d832bddf72 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause7BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause7ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause7BeanCreationExceptionIntegrationTest { +public class Cause7BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java index 8550f307d5..a9f32b6d1a 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause8BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause8ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause8BeanCreationExceptionIntegrationTest { +public class Cause8BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java index ad1ba5f2f1..6af5fb3712 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beancreationexception/Cause9BeanCreationExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause9ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause9BeanCreationExceptionIntegrationTest { +public class Cause9BeanCreationExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java index 8de51a4bf0..1580546fa7 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause1BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1BeanDefinitionStoreExceptionIntegrationTest { +public class Cause1BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java index 8dbc50cda5..ce0db694dc 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause2BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2BeanDefinitionStoreExceptionIntegrationTest { +public class Cause2BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java index 370b67e2fa..c090ac7b5f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/beandefinitionstoreexception/Cause3BeanDefinitionStoreExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3BeanDefinitionStoreExceptionIntegrationTest { +public class Cause3BeanDefinitionStoreExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java index 0f46481116..056e052359 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause1DataIntegrityViolationExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1DataIntegrityViolationExceptionIntegrationTest { +public class Cause1DataIntegrityViolationExceptionManualTest { @Autowired private IParentService service; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java index 0ea0dd2f28..e36a027105 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause2DataIntegrityViolationExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2DataIntegrityViolationExceptionIntegrationTest { +public class Cause2DataIntegrityViolationExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java similarity index 94% rename from spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java index 75d5793910..4194e1c9fe 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/dataintegrityviolationexception/Cause3DataIntegrityViolationExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3DataContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3DataIntegrityViolationExceptionIntegrationTest { +public class Cause3DataIntegrityViolationExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java index 671b0a473e..7ba9618a77 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause1MappingExceptionManualTest.java @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1MappingExceptionIntegrationTest { +public class Cause1MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java index eae5ebd9a2..66923fc6a9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause2MappingExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2MappingExceptionIntegrationTest { +public class Cause2MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java index d6abe7db4f..e6888d1685 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause3MappingExceptionManualTest.java @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3MappingExceptionIntegrationTest { +public class Cause3MappingExceptionManualTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java index 864da76e4b..760d082f54 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/mappingexception/Cause4MappingExceptionManualTest.java @@ -12,7 +12,7 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.Test; -public class Cause4MappingExceptionIntegrationTest { +public class Cause4MappingExceptionManualTest { // tests diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java index 84038e4dcf..b7ed103394 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/CannotGetJdbcConnectionExceptionManualTest.java @@ -18,7 +18,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause5NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class CannotGetJdbcConnectionExceptionIntegrationTest { +public class CannotGetJdbcConnectionExceptionManualTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java index e62a455dd4..b98a210125 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataIntegrityExceptionManualTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataIntegrityExceptionIntegrationTest { +public class DataIntegrityExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java similarity index 97% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java index 8a7c237708..122278580f 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataRetrievalExceptionManualTest.java @@ -17,7 +17,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataRetrievalExceptionIntegrationTest { +public class DataRetrievalExceptionManualTest { @Autowired private DataSource restDataSource; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java index 161bf3252b..4da5f94098 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/DataSourceLookupExceptionManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause4NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class DataSourceLookupExceptionIntegrationTest { +public class DataSourceLookupExceptionManualTest { @Test(expected = DataSourceLookupFailureException.class) public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java similarity index 96% rename from spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java index 316efba0b9..fc420acfe9 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nontransientdataaccessexception/InvalidResourceUsageExceptionManualTest.java @@ -16,7 +16,7 @@ import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class InvalidResourceUsageExceptionIntegrationTest { +public class InvalidResourceUsageExceptionManualTest { @Autowired private IFooService fooService; diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java similarity index 93% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java index 1a9711b2d6..45ffdf9096 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause1NoSuchBeanDefinitionExceptionManualTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause1ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause1NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause1NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java index 90d7317f44..09ed2b4435 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause2NoSuchBeanDefinitionExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause2ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause2NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause2NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java similarity index 91% rename from spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java index 0e2123b7ff..7dc016a568 100644 --- a/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/ex/nosuchbeandefinitionexception/Cause3NoSuchBeanDefinitionExceptionManualTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { Cause3ContextWithJavaConfig.class }, loader = AnnotationConfigContextLoader.class) -public class Cause3NoSuchBeanDefinitionExceptionIntegrationTest { +public class Cause3NoSuchBeanDefinitionExceptionManualTest { @Test public final void givenContextIsInitialized_thenNoException() { diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java index d6c99502d7..91db8210b3 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithJavaManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithJavaConfig.class, PropertiesWithJavaConfigOther.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithJavaIntegrationTest { +public class PropertiesWithJavaManualTest { @Autowired private Environment env; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java index 9fc793fc1b..201e554381 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithMultipleXmlsManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithXmlConfigOne.class, PropertiesWithXmlConfigTwo.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithMultipleXmlsIntegrationTest { +public class PropertiesWithMultipleXmlsManualTest { @Autowired private Environment env; diff --git a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java similarity index 95% rename from spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java rename to spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java index ff5eaab910..a54dd8a3fb 100644 --- a/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlIntegrationTest.java +++ b/spring-exceptions/src/test/java/org/baeldung/properties/core/PropertiesWithXmlManualTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) -public class PropertiesWithXmlIntegrationTest { +public class PropertiesWithXmlManualTest { @Autowired private Environment env; diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml new file mode 100644 index 0000000000..251322295f --- /dev/null +++ b/spring-integration/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + + com.baeldung.samples.spring.integration + baeldungSIsample + 1.0.0.BUILD-SNAPSHOT + jar + + Baeldung Spring Intro + http://www.springsource.org/spring-integration + + + 2.2.1 + + + + UTF-8 + 2.2.4.RELEASE + 1.2.17 + 4.11 + + + + + repo.springsource.org.milestone + Spring Framework Maven Milestone Repository + https://repo.springsource.org/milestone + + + + + + + maven-eclipse-plugin + 2.9 + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + -Xlint:all + true + true + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + com.baeldung.samples.Main + + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.springframework.integration + spring-integration-core + 4.3.4.RELEASE + + + javax.activation + activation + 1.1.1 + true + + + javax.mail + mail + 1.4.7 + + + log4j + log4j + ${log4j.version} + + + org.springframework.integration + spring-integration-twitter + 4.3.4.RELEASE + + + org.springframework.integration + spring-integration-mail + 4.3.4.RELEASE + + + org.springframework.integration + spring-integration-ftp + 4.3.4.RELEASE + + + org.springframework.social + spring-social-core + 1.1.4.RELEASE + + + org.springframework.integration + spring-integration-file + 4.3.4.RELEASE + + + junit + junit + 4.12 + + + diff --git a/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java b/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java new file mode 100644 index 0000000000..4b6ee5d03a --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/endpoints/Activator.java @@ -0,0 +1,7 @@ +package com.baeldung.samples.endpoints; + +public interface Activator { + + public void handleMessage(T input); + +} diff --git a/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java b/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java new file mode 100644 index 0000000000..9b7c2763fc --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/samples/endpoints/ActivatorImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.samples.endpoints; + +import java.io.File; +import java.util.logging.Logger; + +import org.springframework.integration.IntegrationMessageHeaderAccessor; +import org.springframework.messaging.Message; + +public class ActivatorImpl implements Activator> { + + @Override + public void handleMessage(Message input) { + File filePayload = input.getPayload(); + IntegrationMessageHeaderAccessor accessor = new IntegrationMessageHeaderAccessor(input); + Logger.getAnonymousLogger().info("The file size "+filePayload.length()); + Logger.getAnonymousLogger().info("The time of the message "+accessor.getTimestamp()); + + } + +} diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup new file mode 100644 index 0000000000..5687a15f02 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.backup @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml new file mode 100644 index 0000000000..b814e1a6a8 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-context.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml new file mode 100644 index 0000000000..567a3464e7 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-copy-context.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml new file mode 100644 index 0000000000..3bbd59093a --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-file-publish-context.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/source/penguins.jpg b/spring-integration/src/main/resources/source/penguins.jpg new file mode 100644 index 0000000000..030ab8a685 Binary files /dev/null and b/spring-integration/src/main/resources/source/penguins.jpg differ diff --git a/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java new file mode 100644 index 0000000000..96e5a98f41 --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/samples/FileCopyTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.baeldung.samples; + +import org.apache.log4j.Logger; +import org.junit.Test; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.Scanner; + + +/** + * Starts the Spring Context and will initialize the Spring Integration routes. + * + * @author Baeldung + * @since 1.0 + * + */ +public final class FileCopyTest { + + private static final Logger LOGGER = Logger.getLogger(FileCopyTest.class); + + @Test + public void test() throws InterruptedException { + + + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-copy-context.xml"); + + Thread.sleep(5000); + + + } + + @Test + public void publish() throws InterruptedException { + + + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/spring-integration-file-publish-context.xml"); + + Thread.sleep(15000); + + + } +} diff --git a/jooq-spring/.gitignore b/spring-jooq/.gitignore similarity index 100% rename from jooq-spring/.gitignore rename to spring-jooq/.gitignore diff --git a/jooq-spring/README.md b/spring-jooq/README.md similarity index 100% rename from jooq-spring/README.md rename to spring-jooq/README.md diff --git a/jooq-spring/pom.xml b/spring-jooq/pom.xml similarity index 100% rename from jooq-spring/pom.xml rename to spring-jooq/pom.xml diff --git a/jooq-spring/src/main/resources/application.properties b/spring-jooq/src/main/resources/application.properties similarity index 100% rename from jooq-spring/src/main/resources/application.properties rename to spring-jooq/src/main/resources/application.properties diff --git a/jooq-spring/src/main/resources/intro_config.properties b/spring-jooq/src/main/resources/intro_config.properties similarity index 100% rename from jooq-spring/src/main/resources/intro_config.properties rename to spring-jooq/src/main/resources/intro_config.properties diff --git a/jooq-spring/src/main/resources/intro_schema.sql b/spring-jooq/src/main/resources/intro_schema.sql similarity index 100% rename from jooq-spring/src/main/resources/intro_schema.sql rename to spring-jooq/src/main/resources/intro_schema.sql diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/PersistenceContextIntegrationTest.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/introduction/QueryIntegrationTest.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/Application.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java b/spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java similarity index 100% rename from jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java rename to spring-jooq/src/test/java/com/baeldung/jooq/springboot/SpringBootIntegrationTest.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java index f428fc3223..80ce22edd6 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -1,17 +1,16 @@ package com.baeldung.spring.web.config; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import java.util.Set; + public class MainWebAppInitializer implements WebApplicationInitializer { private static final String TMP_FOLDER = "/tmp"; @@ -28,7 +27,6 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("com.baeldung.spring.web.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); // Handles requests into the application diff --git a/spring-rest-docs/pom.xml b/spring-rest-docs/pom.xml index 04ee11d0de..8e758eeb4a 100644 --- a/spring-rest-docs/pom.xml +++ b/spring-rest-docs/pom.xml @@ -63,7 +63,7 @@ maven-surefire-plugin - **/*Documentation.java + **/*IntegrationTest.java diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java similarity index 99% rename from spring-rest-docs/src/test/java/com/example/ApiDocumentation.java rename to spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index 5b753aff0c..0912023fb7 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -38,7 +38,7 @@ import static org.springframework.util.StringUtils.collectionToDelimitedString; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) @WebAppConfiguration -public class ApiDocumentation { +public class ApiDocumentationIntegrationTest { @Rule public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java similarity index 99% rename from spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java rename to spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index 7aea9d303c..1af626d03b 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentation.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -33,7 +33,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) @WebAppConfiguration -public class GettingStartedDocumentation { +public class GettingStartedDocumentationIntegrationTest { @Rule public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD index 760cf41c63..0812a73090 100644 --- a/spring-security-custom-permission/README.MD +++ b/spring-security-custom-permission/README.MD @@ -3,3 +3,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com ###Relevant Articles: - [A Custom Security Expression with Spring Security](http://www.baeldung.com/spring-security-create-new-custom-security-expression) +- [Custom AccessDecisionVoters in Spring Security](http://www.baeldung.com/spring-security-custom-voter) \ No newline at end of file diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml index 6098fe5b65..288cc3d6ba 100644 --- a/spring-security-custom-permission/pom.xml +++ b/spring-security-custom-permission/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE @@ -128,6 +128,7 @@ spring-security-taglibs 4.1.3.RELEASE
+ javax.servlet.jsp.jstl jstl-api @@ -239,6 +240,9 @@ + org.baeldung.Application + + UTF-8 1.8 2.4.0 diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java index b4e8d04b49..2d59fab6be 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java @@ -1,12 +1,17 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; -@SpringBootApplication +@Configuration +@EnableAutoConfiguration +@ComponentScan(excludeFilters = + @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*")) public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/MinuteBasedVoter.java new file mode 100644 index 0000000000..ca9072bcac --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/MinuteBasedVoter.java @@ -0,0 +1,33 @@ +package org.baeldung.voter; + +import java.time.LocalDateTime; +import java.util.Collection; + +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.ConfigAttribute; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; + +public class MinuteBasedVoter implements AccessDecisionVoter { + @Override + public boolean supports(ConfigAttribute attribute) { + return true; + } + + @Override + public boolean supports(Class clazz) { + return true; + } + + @Override + public int vote(Authentication authentication, Object object, Collection collection) { + return authentication + .getAuthorities() + .stream() + .map(GrantedAuthority::getAuthority) + .filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0) + .findAny() + .map(s -> ACCESS_DENIED) + .orElseGet(() -> ACCESS_ABSTAIN); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java new file mode 100644 index 0000000000..046eca9be7 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterApplication.java @@ -0,0 +1,17 @@ +package org.baeldung.voter; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; + +@Configuration +@EnableAutoConfiguration +@ComponentScan(basePackages = {"org.baeldung.voter"}) +public class VoterApplication { + + public static void main(String[] args) { + SpringApplication.run(VoterApplication.class, args); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java new file mode 100644 index 0000000000..e282c794d0 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/VoterMvcConfig.java @@ -0,0 +1,18 @@ +package org.baeldung.voter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Created by ambrusadrianz on 30/09/2016. + */ + +@Configuration +public class VoterMvcConfig extends WebMvcConfigurerAdapter { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("private"); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java new file mode 100644 index 0000000000..3330fda7ec --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/WebSecurityConfig.java @@ -0,0 +1,69 @@ +package org.baeldung.voter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDecisionManager; +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.vote.AuthenticatedVoter; +import org.springframework.security.access.vote.RoleVoter; +import org.springframework.security.access.vote.UnanimousBased; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.access.expression.WebExpressionVoter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import java.util.Arrays; +import java.util.List; + +//@Configuration +//@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + // @formatter: off + auth.inMemoryAuthentication() + .withUser("user").password("pass").roles("USER") + .and() + .withUser("admin").password("pass").roles("ADMIN"); + // @formatter: on + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter: off + http + // needed so our login could work + .csrf() + .disable() + .authorizeRequests() + .anyRequest() + .authenticated() + .accessDecisionManager(accessDecisionManager()) + .antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER") + .and() + .formLogin() + .permitAll() + .and() + .logout() + .permitAll() + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/login"); + // @formatter: on + } + + @Bean + public AccessDecisionManager accessDecisionManager() { + // @formatter: off + List> decisionVoters = + Arrays.asList( + new WebExpressionVoter(), + new RoleVoter(), + new AuthenticatedVoter(), + new MinuteBasedVoter()); + // @formatter: on + return new UnanimousBased(decisionVoters); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java new file mode 100644 index 0000000000..c206df7d1f --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/voter/XmlSecurityConfig.java @@ -0,0 +1,15 @@ +package org.baeldung.voter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +/** + * Created by ambrusadrianz on 09/10/2016. + */ +@Configuration +@ImportResource({"classpath:spring-security.xml"}) +public class XmlSecurityConfig { + public XmlSecurityConfig() { + super(); + } +} diff --git a/spring-security-custom-permission/src/main/resources/spring-security.xml b/spring-security-custom-permission/src/main/resources/spring-security.xml new file mode 100644 index 0000000000..382dbf5dff --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/spring-security.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/resources/templates/private.html b/spring-security-custom-permission/src/main/resources/templates/private.html new file mode 100644 index 0000000000..5af8c7a13e --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/templates/private.html @@ -0,0 +1,10 @@ + + + + Private + + +

Congrats!

+ + \ No newline at end of file diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index b001a86955..145321b2f4 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 071fa14b71..296703c27e 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index 5cd0ed51f3..957a349d3c 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.8.RELEASE diff --git a/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java b/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java new file mode 100644 index 0000000000..445a70f29c --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/example/spring/AnotherBootApp.java @@ -0,0 +1,17 @@ +package org.baeldung.example.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@EnableScheduling +@EnableAutoConfiguration +@ComponentScan("org.baeldung") +public class AnotherBootApp extends WebMvcConfigurerAdapter { + + public static void main(final String[] args) { + SpringApplication.run(AnotherBootApp.class, args); + } +} \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java index 64c84678af..89cec89951 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/CustomRsqlVisitor.java @@ -1,6 +1,5 @@ package org.baeldung.persistence.dao.rsql; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.AndNode; @@ -8,26 +7,26 @@ import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.OrNode; import cz.jirutka.rsql.parser.ast.RSQLVisitor; -public class CustomRsqlVisitor implements RSQLVisitor, Void> { +public class CustomRsqlVisitor implements RSQLVisitor, Void> { - private UserRsqlSpecBuilder builder; + private GenericRsqlSpecBuilder builder; public CustomRsqlVisitor() { - builder = new UserRsqlSpecBuilder(); + builder = new GenericRsqlSpecBuilder(); } @Override - public Specification visit(final AndNode node, final Void param) { + public Specification visit(final AndNode node, final Void param) { return builder.createSpecification(node); } @Override - public Specification visit(final OrNode node, final Void param) { + public Specification visit(final OrNode node, final Void param) { return builder.createSpecification(node); } @Override - public Specification visit(final ComparisonNode node, final Void params) { + public Specification visit(final ComparisonNode node, final Void params) { return builder.createSpecification(node); } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java similarity index 65% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java rename to spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java index 202370a64b..01ec389465 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecBuilder.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java @@ -3,7 +3,6 @@ package org.baeldung.persistence.dao.rsql; import java.util.ArrayList; import java.util.List; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specifications; import cz.jirutka.rsql.parser.ast.ComparisonNode; @@ -11,9 +10,9 @@ import cz.jirutka.rsql.parser.ast.LogicalNode; import cz.jirutka.rsql.parser.ast.LogicalOperator; import cz.jirutka.rsql.parser.ast.Node; -public class UserRsqlSpecBuilder { +public class GenericRsqlSpecBuilder { - public Specifications createSpecification(final Node node) { + public Specifications createSpecification(final Node node) { if (node instanceof LogicalNode) { return createSpecification((LogicalNode) node); } @@ -23,9 +22,9 @@ public class UserRsqlSpecBuilder { return null; } - public Specifications createSpecification(final LogicalNode logicalNode) { - final List> specs = new ArrayList>(); - Specifications temp; + public Specifications createSpecification(final LogicalNode logicalNode) { + final List> specs = new ArrayList>(); + Specifications temp; for (final Node node : logicalNode.getChildren()) { temp = createSpecification(node); if (temp != null) { @@ -33,7 +32,7 @@ public class UserRsqlSpecBuilder { } } - Specifications result = specs.get(0); + Specifications result = specs.get(0); if (logicalNode.getOperator() == LogicalOperator.AND) { for (int i = 1; i < specs.size(); i++) { @@ -50,8 +49,8 @@ public class UserRsqlSpecBuilder { return result; } - public Specifications createSpecification(final ComparisonNode comparisonNode) { - final Specifications result = Specifications.where(new UserRsqlSpecification(comparisonNode.getSelector(), comparisonNode.getOperator(), comparisonNode.getArguments())); + public Specifications createSpecification(final ComparisonNode comparisonNode) { + final Specifications result = Specifications.where(new GenericRsqlSpecification(comparisonNode.getSelector(), comparisonNode.getOperator(), comparisonNode.getArguments())); return result; } diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java similarity index 87% rename from spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java rename to spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java index b7aaa14ba6..6609a87953 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/UserRsqlSpecification.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java @@ -8,18 +8,17 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import org.baeldung.persistence.model.User; import org.springframework.data.jpa.domain.Specification; import cz.jirutka.rsql.parser.ast.ComparisonOperator; -public class UserRsqlSpecification implements Specification { +public class GenericRsqlSpecification implements Specification { private String property; private ComparisonOperator operator; private List arguments; - public UserRsqlSpecification(final String property, final ComparisonOperator operator, final List arguments) { + public GenericRsqlSpecification(final String property, final ComparisonOperator operator, final List arguments) { super(); this.property = property; this.operator = operator; @@ -27,7 +26,7 @@ public class UserRsqlSpecification implements Specification { } @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, final CriteriaBuilder builder) { + public Predicate toPredicate(final Root root, final CriteriaQuery query, final CriteriaBuilder builder) { final List args = castArguments(root); final Object argument = args.get(0); switch (RsqlSearchOperation.getSimpleOperator(operator)) { @@ -73,7 +72,7 @@ public class UserRsqlSpecification implements Specification { // === private - private List castArguments(final Root root) { + private List castArguments(final Root root) { final List args = new ArrayList(); final Class type = root.get(property).getJavaType(); diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java index 0ce8c0300b..fda7b01c7a 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java @@ -1,9 +1,9 @@ package org.baeldung.persistence; -import org.baeldung.persistence.query.JPACriteriaQueryTest; -import org.baeldung.persistence.query.JPAQuerydslTest; -import org.baeldung.persistence.query.JPASpecificationTest; -import org.baeldung.persistence.query.RsqlTest; +import org.baeldung.persistence.query.JPACriteriaQueryIntegrationTest; +import org.baeldung.persistence.query.JPAQuerydslIntegrationTest; +import org.baeldung.persistence.query.JPASpecificationIntegrationTest; +import org.baeldung.persistence.query.RsqlIntegrationTest; import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -11,11 +11,11 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - RsqlTest.class - ,JPASpecificationTest.class + RsqlIntegrationTest.class + ,JPASpecificationIntegrationTest.class ,FooServicePersistenceIntegrationTest.class - ,JPAQuerydslTest.class - ,JPACriteriaQueryTest.class + ,JPAQuerydslIntegrationTest.class + ,JPACriteriaQueryIntegrationTest.class }) // public class PersistenceTestSuite { diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java index 1d0826e6ba..e8e98074c6 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPACriteriaQueryIntegrationTest.java @@ -24,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPACriteriaQueryTest { +public class JPACriteriaQueryIntegrationTest { @Autowired private IUserDAO userApi; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java similarity index 98% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java index d5fbc819fd..d397c3aac4 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPAQuerydslIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPAQuerydslTest { +public class JPAQuerydslIntegrationTest { @Autowired private MyUserRepository repo; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java index 0d8773dd61..8bd4857e85 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/JPASpecificationIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class JPASpecificationTest { +public class JPASpecificationIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java similarity index 99% rename from spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java index e0deb8d4ec..16dfa8a12f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/persistence/query/RsqlIntegrationTest.java @@ -27,7 +27,7 @@ import cz.jirutka.rsql.parser.ast.Node; @ContextConfiguration(classes = { PersistenceConfig.class }) @Transactional @Rollback -public class RsqlTest { +public class RsqlIntegrationTest { @Autowired private UserRepository repository; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 930ab20262..99b391eda1 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.web.context.WebApplicationContext; @WebAppConfiguration @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) -public class LoggerInterceptorTest { +public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 916a849c63..662fc997f9 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -28,7 +28,7 @@ import org.springframework.web.context.WebApplicationContext; @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class SessionTimerInterceptorTest { +public class SessionTimerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java similarity index 97% rename from spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java rename to spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java index ff40c86906..0e8f7c98ed 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/UserInterceptorIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @Transactional @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @WithMockUser(username = "admin", roles = { "USER", "ADMIN" }) -public class UserInterceptorTest { +public class UserInterceptorIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/mutation-testing/README.md b/testing/README.md similarity index 100% rename from mutation-testing/README.md rename to testing/README.md diff --git a/mutation-testing/pom.xml b/testing/pom.xml similarity index 97% rename from mutation-testing/pom.xml rename to testing/pom.xml index cdee59fcb4..aa523d95ef 100644 --- a/mutation-testing/pom.xml +++ b/testing/pom.xml @@ -1,77 +1,77 @@ - - 4.0.0 - com.baeldung - mutation-testing - 0.1-SNAPSHOT - mutation-testing - - - org.pitest - pitest-parent - 1.1.10 - pom - - - junit - junit - 4.9 - - - - - - org.pitest - pitest-maven - 1.1.10 - - - com.baeldung.testing.mutation.* - - - com.baeldung.mutation.test.* - - - - - org.jacoco - jacoco-maven-plugin - 0.7.7.201606060606 - - - - prepare-agent - - - - report - prepare-package - - report - - - - jacoco-check - - check - - - - - PACKAGE - - - LINE - COVEREDRATIO - 0.50 - - - - - - - - - - - + + 4.0.0 + com.baeldung + mutation-testing + 0.1-SNAPSHOT + mutation-testing + + + org.pitest + pitest-parent + 1.1.10 + pom + + + junit + junit + 4.9 + + + + + + org.pitest + pitest-maven + 1.1.10 + + + com.baeldung.testing.mutation.* + + + com.baeldung.mutation.test.* + + + + + org.jacoco + jacoco-maven-plugin + 0.7.7.201606060606 + + + + prepare-agent + + + + report + prepare-package + + report + + + + jacoco-check + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + 0.50 + + + + + + + + + + + diff --git a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java similarity index 97% rename from mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java rename to testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java index 0b166f1557..e264a4c759 100644 --- a/mutation-testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java +++ b/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java @@ -1,15 +1,15 @@ -package com.baeldung.testing.mutation; - -public class Palindrome { - - public boolean isPalindrome(String inputString) { - if (inputString.length() == 0) { - return true; - } else { - char firstChar = inputString.charAt(0); - char lastChar = inputString.charAt(inputString.length() - 1); - String mid = inputString.substring(1, inputString.length() - 1); - return (firstChar == lastChar) && isPalindrome(mid); - } - } -} +package com.baeldung.testing.mutation; + +public class Palindrome { + + public boolean isPalindrome(String inputString) { + if (inputString.length() == 0) { + return true; + } else { + char firstChar = inputString.charAt(0); + char lastChar = inputString.charAt(inputString.length() - 1); + String mid = inputString.substring(1, inputString.length() - 1); + return (firstChar == lastChar) && isPalindrome(mid); + } + } +} diff --git a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java similarity index 96% rename from mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java rename to testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java index 3add6290f6..11ed966b16 100644 --- a/mutation-testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java +++ b/testing/src/test/java/com/baeldung/mutation/test/TestPalindrome.java @@ -1,34 +1,34 @@ -package com.baeldung.mutation.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.baeldung.testing.mutation.Palindrome; - -public class TestPalindrome { - @Test - public void whenEmptyString_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenPalindrom_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); - } - - @Test - public void whenNotPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("box")); - } - - @Test - public void whenNearPalindrom_thanReject(){ - Palindrome palindromeTester = new Palindrome(); - assertFalse(palindromeTester.isPalindrome("neon")); - } -} +package com.baeldung.mutation.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.baeldung.testing.mutation.Palindrome; + +public class TestPalindrome { + @Test + public void whenEmptyString_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenPalindrom_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); + } + + @Test + public void whenNotPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("box")); + } + + @Test + public void whenNearPalindrom_thanReject(){ + Palindrome palindromeTester = new Palindrome(); + assertFalse(palindromeTester.isPalindrome("neon")); + } +} diff --git a/xmlunit2-tutorial/README.md b/xmlunit2/README.md similarity index 100% rename from xmlunit2-tutorial/README.md rename to xmlunit2/README.md diff --git a/xmlunit2-tutorial/pom.xml b/xmlunit2/pom.xml similarity index 96% rename from xmlunit2-tutorial/pom.xml rename to xmlunit2/pom.xml index b4cb684f65..c80e3f37b2 100644 --- a/xmlunit2-tutorial/pom.xml +++ b/xmlunit2/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - xmlunit2-tutorial + xmlunit2 1.0 XMLUnit-2 diff --git a/xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit2-tutorial/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 96% rename from xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java index 175250f47b..5af3d48433 100644 --- a/xmlunit2-tutorial/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java +++ b/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java @@ -1,37 +1,30 @@ package com.baeldung.xmlunit; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; -import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; -import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; - -import java.io.File; -import java.util.Iterator; - import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; -import org.xmlunit.diff.ComparisonControllers; -import org.xmlunit.diff.DefaultNodeMatcher; -import org.xmlunit.diff.Diff; -import org.xmlunit.diff.Difference; -import org.xmlunit.diff.ElementSelectors; +import org.xmlunit.diff.*; import org.xmlunit.validation.Languages; import org.xmlunit.validation.ValidationProblem; import org.xmlunit.validation.ValidationResult; import org.xmlunit.validation.Validator; import org.xmlunit.xpath.JAXPXPathEngine; +import java.io.File; +import java.util.Iterator; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.*; +import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; +import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; +import static org.xmlunit.matchers.HasXPathMatcher.hasXPath; + public class XMLUnitTest { @Test public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() { diff --git a/xmlunit2-tutorial/src/test/resources/control.xml b/xmlunit2/src/test/resources/control.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/control.xml rename to xmlunit2/src/test/resources/control.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xml b/xmlunit2/src/test/resources/students.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xml rename to xmlunit2/src/test/resources/students.xml diff --git a/xmlunit2-tutorial/src/test/resources/students.xsd b/xmlunit2/src/test/resources/students.xsd similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students.xsd rename to xmlunit2/src/test/resources/students.xsd diff --git a/xmlunit2-tutorial/src/test/resources/students_with_error.xml b/xmlunit2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/students_with_error.xml rename to xmlunit2/src/test/resources/students_with_error.xml diff --git a/xmlunit2-tutorial/src/test/resources/teachers.xml b/xmlunit2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/teachers.xml rename to xmlunit2/src/test/resources/teachers.xml diff --git a/xmlunit2-tutorial/src/test/resources/test.xml b/xmlunit2/src/test/resources/test.xml similarity index 100% rename from xmlunit2-tutorial/src/test/resources/test.xml rename to xmlunit2/src/test/resources/test.xml