From d85f1640d70ab55243d4677c17bb02c88443954c Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Sun, 2 Apr 2017 16:35:58 +0530 Subject: [PATCH 1/9] BAEL-716 Junit vs testng improvement --- .../baeldung/junit4vstestng/SortedTests.java | 25 +++++++++++++++++++ .../test/java/baeldung/com/PriorityTest.java | 23 +++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java create mode 100644 testng/src/test/java/baeldung/com/PriorityTest.java diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java new file mode 100644 index 0000000000..1fa4a4e61b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java @@ -0,0 +1,25 @@ +package com.baeldung.junit4vstestng; + +import static org.junit.Assert.assertTrue; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class SortedTests { + + @Test + public void a_givenString_whenChangedtoInt_thenTrue(){ + assertTrue( + Integer.valueOf("10") instanceof Integer); + } + + @Test + public void b_givenInt_whenChangedtoString_thenTrue(){ + assertTrue( + String.valueOf(10) instanceof String); + } + +} diff --git a/testng/src/test/java/baeldung/com/PriorityTest.java b/testng/src/test/java/baeldung/com/PriorityTest.java new file mode 100644 index 0000000000..34f2d6fe47 --- /dev/null +++ b/testng/src/test/java/baeldung/com/PriorityTest.java @@ -0,0 +1,23 @@ +package baeldung.com; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class PriorityTest { + + private String testString = "10"; + private int testInt = 23; + + @Test(priority = 1) + public void givenString_whenChangedToInt_thenCorrect() { + Assert.assertTrue( + Integer.valueOf(testString) instanceof Integer); + } + + @Test(priority = 2) + public void givenInt_whenChangedToString_thenCorrect() { + Assert.assertTrue( + String.valueOf(testInt) instanceof String); + } + +} From c817aec2dc5303da4aca06bd222b6c21704cee24 Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Sun, 2 Apr 2017 21:20:31 +0530 Subject: [PATCH 2/9] BAEL-716 Junit vs testng improvement updated formatting --- .../com/baeldung/junit4vstestng/SortedTests.java | 15 ++++++--------- .../src/test/java/baeldung/com/PriorityTest.java | 6 ++---- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java index 1fa4a4e61b..fe0ec1469c 100644 --- a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java @@ -6,20 +6,17 @@ import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; - @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SortedTests { - + @Test - public void a_givenString_whenChangedtoInt_thenTrue(){ - assertTrue( - Integer.valueOf("10") instanceof Integer); + public void a_givenString_whenChangedtoInt_thenTrue() { + assertTrue(Integer.valueOf("10") instanceof Integer); } - + @Test - public void b_givenInt_whenChangedtoString_thenTrue(){ - assertTrue( - String.valueOf(10) instanceof String); + public void b_givenInt_whenChangedtoString_thenTrue() { + assertTrue(String.valueOf(10) instanceof String); } } diff --git a/testng/src/test/java/baeldung/com/PriorityTest.java b/testng/src/test/java/baeldung/com/PriorityTest.java index 34f2d6fe47..d014d5c920 100644 --- a/testng/src/test/java/baeldung/com/PriorityTest.java +++ b/testng/src/test/java/baeldung/com/PriorityTest.java @@ -10,14 +10,12 @@ public class PriorityTest { @Test(priority = 1) public void givenString_whenChangedToInt_thenCorrect() { - Assert.assertTrue( - Integer.valueOf(testString) instanceof Integer); + Assert.assertTrue(Integer.valueOf(testString) instanceof Integer); } @Test(priority = 2) public void givenInt_whenChangedToString_thenCorrect() { - Assert.assertTrue( - String.valueOf(testInt) instanceof String); + Assert.assertTrue(String.valueOf(testInt) instanceof String); } } From 4d08f3db6d0e990d91fb146d141beb59975972df Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 3 Apr 2017 16:14:11 +0200 Subject: [PATCH 3/9] Refactor Analyzer examples (#1579) * Refactor Analyzer examples * Refactor Analyzer examples --- .../MyBeanNotOfRequiredTypeFailureAnalyzer.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java index 2f83ad6b57..2bbae8944a 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java @@ -4,7 +4,8 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; -public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer { +public class MyBeanNotOfRequiredTypeFailureAnalyzer + extends AbstractFailureAnalyzer { @Override protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { @@ -12,14 +13,16 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnaly } private String getDescription(BeanNotOfRequiredTypeException ex) { - return "The bean " + ex.getBeanName() // - + " could not be injected as " + ex.getRequiredType().getName() // - + " because it is of type " + ex.getActualType().getName(); + return String.format("The bean %s could not be injected as %s because it is of type %s", + ex.getBeanName(), + ex.getRequiredType().getName(), + ex.getActualType().getName()); } private String getAction(BeanNotOfRequiredTypeException ex) { - return "Consider creating a bean with name "+ ex.getBeanName() // - + " of type " + ex.getRequiredType().getName(); + return String.format("Consider creating a bean with name %s of type %s", + ex.getBeanName(), + ex.getRequiredType().getName()); } } From e7cc45644ebf45fb9725b78318a9e1faa7f934a0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 3 Apr 2017 18:03:10 +0200 Subject: [PATCH 4/9] Optimize build (#1582) --- ...t.java => JsoupParserIntegrationTest.java} | 4 +- pom.xml | 1 + spring-data-gemfire/pom.xml | 6 +++ ...=> EmployeeRepositoryIntegrationTest.java} | 6 +-- spring-data-javaslang/pom.xml | 17 +++++-- ...gTests.java => SpringIntegrationTest.java} | 45 ++++++++++--------- 6 files changed, 50 insertions(+), 29 deletions(-) rename jsoup/src/test/java/com/baeldung/jsoup/{JsoupParserTest.java => JsoupParserIntegrationTest.java} (98%) rename spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/{EmployeeRepositoryTest.java => EmployeeRepositoryIntegrationTest.java} (96%) rename spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/{SpringTests.java => SpringIntegrationTest.java} (80%) diff --git a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java similarity index 98% rename from jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java rename to jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java index ba6d7358bc..dadd57b0ed 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java @@ -14,9 +14,9 @@ import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class JsoupParserTest { +public class JsoupParserIntegrationTest { - Document doc; + private Document doc; @Before public void setUp() throws IOException { diff --git a/pom.xml b/pom.xml index c8d060ec04..a6b46a0e39 100644 --- a/pom.xml +++ b/pom.xml @@ -129,6 +129,7 @@ spring-data-couchbase-2 spring-data-dynamodb spring-data-elasticsearch + spring-data-javaslang spring-data-mongodb spring-data-neo4j spring-data-redis diff --git a/spring-data-gemfire/pom.xml b/spring-data-gemfire/pom.xml index f387b04651..eb450ebc81 100644 --- a/spring-data-gemfire/pom.xml +++ b/spring-data-gemfire/pom.xml @@ -75,6 +75,12 @@ org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + diff --git a/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryTest.java b/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java similarity index 96% rename from spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryTest.java rename to spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java index 8714ad2d81..26f7bc8a4e 100644 --- a/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryTest.java +++ b/spring-data-gemfire/src/test/java/com/baeldung/spring/data/gemfire/repository/EmployeeRepositoryIntegrationTest.java @@ -18,13 +18,13 @@ import static junit.framework.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) -public class EmployeeRepositoryTest { +public class EmployeeRepositoryIntegrationTest { - @Autowired + @Autowired private EmployeeRepository employeeRepository; @Autowired - FunctionExecution execution; + private FunctionExecution execution; @Test public void whenEmployeeIsSaved_ThenAbleToRead(){ diff --git a/spring-data-javaslang/pom.xml b/spring-data-javaslang/pom.xml index c265e893cc..76fbce1e2e 100644 --- a/spring-data-javaslang/pom.xml +++ b/spring-data-javaslang/pom.xml @@ -1,8 +1,8 @@ 4.0.0 - spring-data-javaslangb - spring-data-javaslangb + spring-data-javaslang + spring-data-javaslang 0.0.1-SNAPSHOT UTF-8 @@ -65,7 +65,18 @@ ${project.build.testSourceDirectory} - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LiveTest.java + + + + diff --git a/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringTests.java b/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java similarity index 80% rename from spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringTests.java rename to spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java index 59a6c120fa..7a23fa1ef2 100644 --- a/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringTests.java +++ b/spring-data-javaslang/src/test/java/com/baeldung/spring_data_tests/SpringIntegrationTest.java @@ -1,34 +1,33 @@ package com.baeldung.spring_data_tests; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.baeldung.spring_data_app.MainApp; import com.baeldung.spring_data.model.Book; import com.baeldung.spring_data.model.JavaBook; import com.baeldung.spring_data.repository.BookRepository; import com.baeldung.spring_data.repository.JavaBookRepository; - +import com.baeldung.spring_data_app.MainApp; +import javaslang.collection.List; +import javaslang.collection.Seq; +import javaslang.control.Option; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; -import javaslang.collection.Seq; -import javaslang.collection.List; -import javaslang.control.Option; - import java.util.ArrayList; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @SpringBootTest(classes = MainApp.class,webEnvironment = WebEnvironment.NONE) -public class SpringTests { +public class SpringIntegrationTest { @Autowired - JavaBookRepository javaRepository; + private JavaBookRepository javaRepository; @Autowired - BookRepository repository; + private BookRepository repository; @Test public void should_return_seq(){ @@ -38,7 +37,8 @@ public class SpringTests { testBook.setAuthors(authors); Book book = repository.save(testBook); Option> books = repository.findByTitleContaining("Seq Test"); - assert(!books.isEmpty()); + + assertThat(books).isNotEmpty(); } @@ -50,8 +50,9 @@ public class SpringTests { testBook.setAuthors(authors); Book book = repository.save(testBook); Option retBook = repository.findById(1L); - assert(retBook.isDefined() && !retBook.isEmpty()); - assert(retBook.get() != null); + + assertThat(retBook.isDefined()).isTrue(); + assertThat(retBook).isNotEmpty(); } @Test @@ -64,9 +65,11 @@ public class SpringTests { testBook.setAuthors(authors); JavaBook book = javaRepository.save(testBook); java.util.List books = javaRepository.findByTitleContaining("Seq"); - assert(!books.isEmpty()); - assert(books.size() == 1); - assert(books.get(0).getTitle().equals("Javaslang in Spring Data Seq Return")); + assertThat(books) + .isNotEmpty() + .hasSize(1) + .extracting("title") + .contains("Javaslang in Spring Data Seq Return"); } @Test @@ -79,8 +82,8 @@ public class SpringTests { testBook.setAuthors(authors); JavaBook book = javaRepository.save(testBook); JavaBook retBook = javaRepository.findById(1L); - assert(retBook != null); - assert(retBook.getId() == 1L); - assert(retBook.getTitle().contains("Data")); + + assertThat(retBook.getId()).isEqualTo(1L); + assertThat(retBook.getTitle()).isEqualTo("Javaslang in Spring Data"); } } \ No newline at end of file From 2a76b9c65689b05054ae2d6d82dd77ef73496586 Mon Sep 17 00:00:00 2001 From: gitterjim-I Date: Mon, 3 Apr 2017 23:30:45 +0100 Subject: [PATCH 5/9] change test names, bael-667 (#1581) * article Bael-667 initial commit. * Switch to use logging framework for output. * Make code more concise. Refactor as suggested. * modify test method names --- .../list/flattennestedlist/FlattenNestedListTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java index b7939d09da..285b217156 100644 --- a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java +++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java @@ -17,7 +17,7 @@ public class FlattenNestedListTest { List> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four")); @Test - public void givenString_flattenNestedList1() { + public void givenNestedList_thenFlattenNestedListImperative() { List ls = flattenListOfListsImperatively(lol); assertNotNull(ls); @@ -27,7 +27,7 @@ public class FlattenNestedListTest { } @Test - public void givenString_flattenNestedList2() { + public void givenNestedList_thenFlattenNestedListStream() { List ls = flattenListOfListsStream(lol); assertNotNull(ls); From 8da820b35a34ae0a5cc6cc54528032a4ee7e2ad7 Mon Sep 17 00:00:00 2001 From: Wim Deblauwe Date: Tue, 4 Apr 2017 00:35:35 +0200 Subject: [PATCH 6/9] BAEL-87 - @JsonComponent in Spring Boot (#1519) --- .../java/org/baeldung/jsoncomponent/User.java | 15 ++++++ .../jsoncomponent/UserCombinedSerializer.java | 46 +++++++++++++++++++ .../jsoncomponent/UserJsonDeserializer.java | 22 +++++++++ .../jsoncomponent/UserJsonSerializer.java | 29 ++++++++++++ .../UserJsonDeserializerTest.java | 27 +++++++++++ .../jsoncomponent/UserJsonSerializerTest.java | 27 +++++++++++ 6 files changed, 166 insertions(+) create mode 100644 spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java create mode 100644 spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java create mode 100644 spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java create mode 100644 spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java create mode 100644 spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerTest.java create mode 100644 spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerTest.java diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java new file mode 100644 index 0000000000..8961874526 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/User.java @@ -0,0 +1,15 @@ +package org.baeldung.jsoncomponent; + +import javafx.scene.paint.Color; + +public class User { + private final Color favoriteColor; + + public User(Color favoriteColor) { + this.favoriteColor = favoriteColor; + } + + public Color getFavoriteColor() { + return favoriteColor; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java new file mode 100644 index 0000000000..302b0dce61 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java @@ -0,0 +1,46 @@ +package org.baeldung.jsoncomponent; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.node.TextNode; +import javafx.scene.paint.Color; +import org.springframework.boot.jackson.JsonComponent; + +import java.io.IOException; + +@JsonComponent +public class UserCombinedSerializer { + public static class UserJsonSerializer extends JsonSerializer { + + @Override + public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { + jsonGenerator.writeStartObject(); + jsonGenerator.writeStringField("favoriteColor", + getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeEndObject(); + } + + private static String getColorAsWebColor(Color color) { + int r = (int) Math.round(color.getRed() * 255.0); + int g = (int) Math.round(color.getGreen() * 255.0); + int b = (int) Math.round(color.getBlue() * 255.0); + return String.format("#%02x%02x%02x", r, g, b); + } + } + + @JsonComponent + public static class UserJsonDeserializer extends JsonDeserializer { + @Override + public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); + return new User(Color.web(favoriteColor.asText())); + } + } +} diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java new file mode 100644 index 0000000000..d18de7e3f1 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java @@ -0,0 +1,22 @@ +package org.baeldung.jsoncomponent; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.node.TextNode; +import javafx.scene.paint.Color; +import org.springframework.boot.jackson.JsonComponent; + +import java.io.IOException; + +@JsonComponent +public class UserJsonDeserializer extends JsonDeserializer { + @Override + public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { + TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); + return new User(Color.web(favoriteColor.asText())); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java new file mode 100644 index 0000000000..d90f662a4b --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java @@ -0,0 +1,29 @@ +package org.baeldung.jsoncomponent; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import javafx.scene.paint.Color; +import org.springframework.boot.jackson.JsonComponent; + +import java.io.IOException; + +@JsonComponent +public class UserJsonSerializer extends JsonSerializer { + + @Override + public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { + jsonGenerator.writeStartObject(); + jsonGenerator.writeStringField("favoriteColor", + getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeEndObject(); + } + + private static String getColorAsWebColor(Color color) { + int r = (int) Math.round(color.getRed() * 255.0); + int g = (int) Math.round(color.getGreen() * 255.0); + int b = (int) Math.round(color.getBlue() * 255.0); + return String.format("#%02x%02x%02x", r, g, b); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerTest.java b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerTest.java new file mode 100644 index 0000000000..51c1c72ea3 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonDeserializerTest.java @@ -0,0 +1,27 @@ +package org.baeldung.jsoncomponent; + +import com.fasterxml.jackson.databind.ObjectMapper; +import javafx.scene.paint.Color; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.JsonTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +@JsonTest +@RunWith(SpringRunner.class) +public class UserJsonDeserializerTest { + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void testDeserialize() throws IOException { + User user = objectMapper.readValue("{\"favoriteColor\":\"#f0f8ff\"}", User.class); + assertEquals(Color.ALICEBLUE, user.getFavoriteColor()); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerTest.java b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerTest.java new file mode 100644 index 0000000000..c85af4a17f --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerTest.java @@ -0,0 +1,27 @@ +package org.baeldung.jsoncomponent; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import javafx.scene.paint.Color; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.JsonTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@JsonTest +@RunWith(SpringRunner.class) +public class UserJsonSerializerTest { + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void testSerialization() throws JsonProcessingException { + String json = objectMapper.writeValueAsString(new User(Color.ALICEBLUE)); + assertEquals("{\"favoriteColor\":\"#f0f8ff\"}", json); + } +} \ No newline at end of file From a4f4301196de133395001482597c4d6267ff7fbf Mon Sep 17 00:00:00 2001 From: Yasin Date: Tue, 4 Apr 2017 15:58:51 +0530 Subject: [PATCH 7/9] BAEL-729 Adding custom info to actuator's /info endpoint (#1584) * yasin.bhojawala@gmail.com Evaluation article on Different Types of Bean Injection in Spring * Revert "yasin.bhojawala@gmail.com" This reverts commit 963cc51a7a15b75b550108fe4e198cd65a274032. * Fixing compilation error and removing unused import * Introduction to Java9 StackWalking API - yasin.bhojawala@gmail.com Code examples for the article "Introduction to Java9 StackWalking API" * BAEL-608 Introduction to Java9 StackWalking API * BAEL-608 Introduction to Java9 StackWalking API changing the test names to BDD style * BAEL-608 Introduction to Java9 StackWalking API correcting the typo * BAEL-608 Introduction to Java9 StackWalking API improving method names * BAEL-608 Introduction to Java9 StackWalking API test method names improvements * BAEL-718 Quick intro to javatuples * merging pom from master * BAEL-722 Intro to JSONassert * BAEL-722 Intro to JSONassert Updated to 1.5.0 * BAEL-745 Quick Math.pow example * BAEL-729 Adding custom info to actuator's /info endpoint --- .../java/org/baeldung/boot/model/User.java | 41 +++++++++++++++++++ .../boot/repository/UserRepository.java | 10 +++++ .../info/TotalUsersInfoContributor.java | 26 ++++++++++++ .../src/main/resources/application.properties | 5 ++- spring-boot/src/main/resources/data.sql | 5 +++ spring-boot/src/main/resources/schema.sql | 6 +++ 6 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/main/java/org/baeldung/boot/model/User.java create mode 100644 spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java create mode 100644 spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java create mode 100644 spring-boot/src/main/resources/data.sql create mode 100644 spring-boot/src/main/resources/schema.sql diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/User.java b/spring-boot/src/main/java/org/baeldung/boot/model/User.java new file mode 100644 index 0000000000..f60ac86fe4 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/model/User.java @@ -0,0 +1,41 @@ +package org.baeldung.boot.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer status; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java new file mode 100644 index 0000000000..3a419a65bd --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/repository/UserRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + public int countByStatus(int status); +} diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java new file mode 100644 index 0000000000..790584644f --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -0,0 +1,26 @@ +package org.baeldung.endpoints.info; + +import java.util.HashMap; +import java.util.Map; + +import org.baeldung.boot.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.info.Info; +import org.springframework.boot.actuate.info.InfoContributor; +import org.springframework.stereotype.Component; + +@Component +public class TotalUsersInfoContributor implements InfoContributor { + + @Autowired + UserRepository userRepository; + + @Override + public void contribute(Info.Builder builder) { + Map userDetails = new HashMap<>(); + userDetails.put("active", userRepository.countByStatus(1)); + userDetails.put("inactive", userRepository.countByStatus(0)); + + builder.withDetail("users", userDetails); + } +} diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 1ffc95849d..84315a2477 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -2,7 +2,9 @@ server.port=8080 server.contextPath=/springbootapp management.port=8081 management.address=127.0.0.1 - +#debug=true +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto = update endpoints.shutdown.enabled=true endpoints.jmx.domain=Spring Sample Application @@ -22,6 +24,7 @@ http.mappers.jsonPrettyPrint=true info.app.name=Spring Sample Application info.app.description=This is my first spring boot application G1 info.app.version=1.0.0 +info.java-vendor = ${java.specification.vendor} ## Spring Security Configurations security.user.name=admin1 diff --git a/spring-boot/src/main/resources/data.sql b/spring-boot/src/main/resources/data.sql new file mode 100644 index 0000000000..c44034c739 --- /dev/null +++ b/spring-boot/src/main/resources/data.sql @@ -0,0 +1,5 @@ +insert into users values (1, 'Alex', 1); +insert into users values (2, 'Bob', 1); +insert into users values (3, 'John', 0); +insert into users values (4, 'Harry', 0); +insert into users values (5, 'Smith', 1); \ No newline at end of file diff --git a/spring-boot/src/main/resources/schema.sql b/spring-boot/src/main/resources/schema.sql new file mode 100644 index 0000000000..27859c1652 --- /dev/null +++ b/spring-boot/src/main/resources/schema.sql @@ -0,0 +1,6 @@ +create table USERS( + ID int not null AUTO_INCREMENT, + NAME varchar(100) not null, + STATUS int, + PRIMARY KEY ( ID ) +); \ No newline at end of file From 50ff1d18c481668f4b1edd2d4af4369c9564e5ba Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Tue, 4 Apr 2017 16:02:55 +0530 Subject: [PATCH 8/9] quick-guide-to-the-java-stringtokenizer (#1587) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java * Joining/Splitting Strings with Java and Stream API * adding more join/split functionality * changing package name * testcase change * adding webutils * adding testcase for WebUtils and ServletRequestUtils * adding testcase * spring-security-stormpath * adding ratpack module * adding pom.xml * adding following modules with updated testcase : DB, Filter, Json * adding spring-boot custom banner tutorial * changing banner format in plain text * Delete banner.txt~ * Delete b.txt~ * CORS in JAX-RS * ratpack with google guice * adding factory instance example * quick-guide-to-the-java-stringtokenizer * Update Application.java * Delete MovieCrudService.java~ --- .../baeldung/stringtokenizer/Application.java | 21 +++++++++++++ .../stringtokenizer/ApplicationTest.java | 30 +++++++++++++++++++ .../main/java/com/baeldung/Application.java | 1 + .../java/com/baeldung/filter/CORSFilter.java | 18 +++++++++++ 4 files changed, 70 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/stringtokenizer/Application.java create mode 100644 core-java/src/test/java/com/baeldung/stringtokenizer/ApplicationTest.java create mode 100644 resteasy/src/main/java/com/baeldung/filter/CORSFilter.java diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/Application.java b/core-java/src/main/java/com/baeldung/stringtokenizer/Application.java new file mode 100644 index 0000000000..caa7ef06da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stringtokenizer/Application.java @@ -0,0 +1,21 @@ +package com.baeldung.stringtokenizer; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +public class Application { + + public List getTokens(String str) { + List tokens = new ArrayList(); +// StringTokenizer tokenizer = new StringTokenizer( str ); + StringTokenizer tokenizer = new StringTokenizer( str , "," ); +// StringTokenizer tokenizer = new StringTokenizer( str , "," , true ); + while (tokenizer.hasMoreElements()) { + tokens.add( tokenizer.nextToken() ); +// tokens.add( tokenizer.nextToken( "," ) ); + } + return tokens; + } + +} diff --git a/core-java/src/test/java/com/baeldung/stringtokenizer/ApplicationTest.java b/core-java/src/test/java/com/baeldung/stringtokenizer/ApplicationTest.java new file mode 100644 index 0000000000..5e3df5b303 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stringtokenizer/ApplicationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.stringtokenizer; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ApplicationTest { + + Application application = new Application(); + List expectedTokens = new ArrayList(); + + @Before + public void init() { + expectedTokens.add( "Welcome" ); + expectedTokens.add( "to" ); + expectedTokens.add( "baeldung.com" ); + } + + @Test + public void givenString_thenGetListOfString() { + String str = "Welcome,to,baeldung.com"; + List actualTokens = application.getTokens(str); + assertEquals(expectedTokens, actualTokens); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/Application.java b/ratpack/src/main/java/com/baeldung/Application.java index 94709e88e9..7f46b241ea 100644 --- a/ratpack/src/main/java/com/baeldung/Application.java +++ b/ratpack/src/main/java/com/baeldung/Application.java @@ -46,3 +46,4 @@ public class Application { } } + diff --git a/resteasy/src/main/java/com/baeldung/filter/CORSFilter.java b/resteasy/src/main/java/com/baeldung/filter/CORSFilter.java new file mode 100644 index 0000000000..16562d4359 --- /dev/null +++ b/resteasy/src/main/java/com/baeldung/filter/CORSFilter.java @@ -0,0 +1,18 @@ +package com.baeldung.filter; + +import java.io.IOException; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; + +public class CORSFilter implements ContainerResponseFilter { + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); + + } + +} From eb26f83cd18ce3c4ab05dfecc4b0df89f2b8e800 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Tue, 4 Apr 2017 22:48:41 +0200 Subject: [PATCH 9/9] Bael 770 jetty (#1548) * BAEL-770 add jetty simple test case * BAEL-770 jetty async and blocking servlets * BAEL-766 reorder --- libraries/pom.xml | 25 +++++++- .../java/com/baeldung/jetty/AsyncServlet.java | 42 ++++++++++++++ .../com/baeldung/jetty/BlockingServlet.java | 17 ++++++ .../java/com/baeldung/jetty/JettyServer.java | 32 ++++++++++ .../java/com/baeldung/jetty/JettyTest.java | 58 +++++++++++++++++++ 5 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java create mode 100644 libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java create mode 100644 libraries/src/main/java/com/baeldung/jetty/JettyServer.java create mode 100644 libraries/src/test/java/com/baeldung/jetty/JettyTest.java diff --git a/libraries/pom.xml b/libraries/pom.xml index 11295230b4..0f33c42dc4 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> parent-modules com.baeldung @@ -72,6 +72,26 @@ javers-core ${javers.version} + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-io + commons-io + ${commons.io.version} + @@ -84,6 +104,9 @@ 3.6.2 1.5.0 3.1.0 + 9.4.2.v20170220 + 4.5.3 + 2.5 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java b/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java new file mode 100644 index 0000000000..d1bddd097f --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jetty/AsyncServlet.java @@ -0,0 +1,42 @@ +package com.baeldung.jetty; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +public class AsyncServlet extends HttpServlet { + private static final String HEAVY_RESOURCE = "This is some heavy resource that will be served in an async way"; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8)); + + AsyncContext async = request.startAsync(); + ServletOutputStream out = response.getOutputStream(); + out.setWriteListener(new WriteListener() { + @Override + public void onWritePossible() throws IOException { + while (out.isReady()) { + if (!content.hasRemaining()) { + response.setStatus(200); + async.complete(); + return; + } + out.write(content.get()); + } + } + + @Override + public void onError(Throwable t) { + getServletContext().log("Async Error", t); + async.complete(); + } + }); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java new file mode 100644 index 0000000000..f1de71beeb --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java @@ -0,0 +1,17 @@ +package com.baeldung.jetty; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class BlockingServlet extends HttpServlet { + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().println("{ \"status\": \"ok\"}"); + } +} + diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java new file mode 100644 index 0000000000..1365de866a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java @@ -0,0 +1,32 @@ +package com.baeldung.jetty; + +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletHandler; + +public class JettyServer { + + private Server server; + + public void start() throws Exception { + + server = new Server(); + ServerConnector connector = new ServerConnector(server); + connector.setPort(8090); + server.setConnectors(new Connector[]{connector}); + + ServletHandler servletHandler = new ServletHandler(); + server.setHandler(servletHandler); + + servletHandler.addServletWithMapping(BlockingServlet.class, "/status"); + servletHandler.addServletWithMapping(AsyncServlet.class, "/heavy/async"); + + server.start(); + + } + + public void stop() throws Exception { + server.stop(); + } +} diff --git a/libraries/src/test/java/com/baeldung/jetty/JettyTest.java b/libraries/src/test/java/com/baeldung/jetty/JettyTest.java new file mode 100644 index 0000000000..caf70f9af3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jetty/JettyTest.java @@ -0,0 +1,58 @@ +package com.baeldung.jetty; + + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class JettyTest { + private JettyServer jettyServer; + + @Before + public void setup() throws Exception { + jettyServer = new JettyServer(); + jettyServer.start(); + } + + @After + public void cleanup() throws Exception { + Thread.sleep(2000); + jettyServer.stop(); + } + + @Test + public void givenServer_whenSendRequestToBlockingServlet_thenReturnStatusOK() throws Exception { + //given + String url = "http://localhost:8090/status"; + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(url); + HttpResponse response = client.execute(request); + + //then + assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); + + } + + @Test + public void givenServer_whenSendRequestToNonBlockingServlet_thenReturnStatusOK() throws Exception { + //when + String url = "http://localhost:8090/heavy/async"; + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(url); + HttpResponse response = client.execute(request); + + //then + assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); + String responseContent = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); + assertThat(responseContent).isEqualTo("This is some heavy resource that will be served in an async way"); + } +}