diff --git a/.gitignore b/.gitignore index b083ee9..6f5f31d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,26 @@ -okhttp-examples/.settings/org.eclipse.core.resources.prefs -okhttp-examples/.settings/org.eclipse.m2e.core.prefs +# Eclipse +.project +.classpath +.settings/ + +# Idea +.idea/ +*.iml +*.iws +*.ipr + +# OS +Thumbs.db +.DS_Store + +# Maven +target/ + +# Build +out/ +build/ +bin/ + + +# Others +*.log diff --git a/Book-RESTful-Service/.classpath b/Book-RESTful-Service/.classpath deleted file mode 100644 index af1430b..0000000 --- a/Book-RESTful-Service/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Book-RESTful-Service/.gitignore b/Book-RESTful-Service/.gitignore deleted file mode 100644 index b83d222..0000000 --- a/Book-RESTful-Service/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/Book-RESTful-Service/.project b/Book-RESTful-Service/.project deleted file mode 100644 index 673c4ba..0000000 --- a/Book-RESTful-Service/.project +++ /dev/null @@ -1,35 +0,0 @@ - - - book-rest-service - - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - - diff --git a/Book-RESTful-Service/.settings/org.eclipse.core.resources.prefs b/Book-RESTful-Service/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index f9fe345..0000000 --- a/Book-RESTful-Service/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/test/java=UTF-8 -encoding/=UTF-8 diff --git a/Book-RESTful-Service/.settings/org.eclipse.jdt.core.prefs b/Book-RESTful-Service/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/Book-RESTful-Service/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Book-RESTful-Service/.settings/org.eclipse.m2e.core.prefs b/Book-RESTful-Service/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/Book-RESTful-Service/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/Book-RESTful-Service/.settings/org.eclipse.wst.common.project.facet.core.xml b/Book-RESTful-Service/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index d858295..0000000 --- a/Book-RESTful-Service/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/Book-RESTful-Service/README.md b/Book-RESTful-Service/README.md index a6e2973..240e1c3 100644 --- a/Book-RESTful-Service/README.md +++ b/Book-RESTful-Service/README.md @@ -17,15 +17,26 @@ Open the **Application.java** This RESTful ws provides API for all below sub projects: -###[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) -###[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) -###[Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) -###[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) -###[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) -###[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) -###[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) -###[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) -###[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) -###[Java REST Client Using Retrofit 2](http://howtoprogram.xyz/2016/10/17/java-rest-client-using-retrofit-2/) -###[Upload a File with OkHttp](http://howtoprogram.xyz/2016/11/21/upload-file-okhttp/) -###[File Uploading with Open Feign](http://howtoprogram.xyz/2016/12/29/file-uploading-open-feign/) \ No newline at end of file +### [Simple Java REST Client Using java.net.URL package](https://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) + +### [Java REST Client Using Spring RestTemplate](https://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) + +### [Java REST Client Using Apache HttpClient](https://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) + +### [Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) + +### [Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) + +### [Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) + +### [Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) + +### [Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) + +### [Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) + +### [Java REST Client Using Retrofit 2](http://howtoprogram.xyz/2016/10/17/java-rest-client-using-retrofit-2/) + +### [Upload a File with OkHttp](http://howtoprogram.xyz/2016/11/21/upload-file-okhttp/) + +### [File Uploading with Open Feign](http://howtoprogram.xyz/2016/12/29/file-uploading-open-feign/) diff --git a/Java-JsonPojo-Example/.classpath b/Java-JsonPojo-Example/.classpath deleted file mode 100644 index 0a1dadd..0000000 --- a/Java-JsonPojo-Example/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Java-JsonPojo-Example/.gitignore b/Java-JsonPojo-Example/.gitignore deleted file mode 100644 index b83d222..0000000 --- a/Java-JsonPojo-Example/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/Java-JsonPojo-Example/.project b/Java-JsonPojo-Example/.project deleted file mode 100644 index 8b094d7..0000000 --- a/Java-JsonPojo-Example/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - java-json-pojo-example - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/Java-JsonPojo-Example/.settings/org.eclipse.jdt.core.prefs b/Java-JsonPojo-Example/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index abec6ca..0000000 --- a/Java-JsonPojo-Example/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/Java-JsonPojo-Example/.settings/org.eclipse.m2e.core.prefs b/Java-JsonPojo-Example/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/Java-JsonPojo-Example/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/Java-JsonPojo-Example/README.md b/Java-JsonPojo-Example/README.md index bbbf546..8db51b1 100644 --- a/Java-JsonPojo-Example/README.md +++ b/Java-JsonPojo-Example/README.md @@ -1,7 +1,7 @@ # Java JsonPojo Examples -## 1. Import source code into Eclipse +### 1. Import source code into Eclipse Menu **File –> Import –> Maven –> Existing Maven Projects** @@ -9,20 +9,27 @@ Browse to your source code location Click **Finish** button to finish the importing -## 2. Run the example +### 2. Run the example -Open the **JsonPojoUtils.java** +Open the GsonTest.java and JacksonTest.java -**Right click -> Run As -> Java Application** or use the shortcut: **Alt+Shift+x, j** to start the main method -Source code are described in **[Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/)** +**Right click -> Run As -> Java Application** or use the shortcut: **Alt+Shift+x, t** to start the JUnit test methods. +Source code are described in [Convert Java Objects To JSON And Vice Versa With Jackson and Gson](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) -## Related articles -###[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) -###[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) -###[Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) -###[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) -###[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) -###[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) -###[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) -###[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) -###[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) \ No newline at end of file +### Related articles + +[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) + +[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) + +[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) + +[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) + +[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) + +[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) + +[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) + +[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) diff --git a/Java-JsonPojo-Example/pom.xml b/Java-JsonPojo-Example/pom.xml index c599788..67da9e6 100644 --- a/Java-JsonPojo-Example/pom.xml +++ b/Java-JsonPojo-Example/pom.xml @@ -6,7 +6,13 @@ 0.0.1-SNAPSHOT + UTF-8 1.8 + 4.12 + 5.0.0 + ${junit.version}.0 + 5.0.0 + 1.0.0 @@ -15,5 +21,73 @@ jackson-databind 2.7.5 + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + 2.9.0 + + + + com.google.code.gson + gson + 2.8.1 + compile + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + junit + junit + ${junit.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + + + maven-compiler-plugin + 3.7.0 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19.1 + + + **/Test*.java + **/*Test.java + **/*Tests.java + **/*TestCase.java + + + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + \ No newline at end of file diff --git a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java b/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java index ceb43f2..95e1a6c 100644 --- a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java +++ b/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java @@ -1,75 +1,87 @@ package com.howtoprogram.jsonpojo; +import java.time.LocalDate; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; public class Book { - private Long id; - private String name; - private String author; - - - public Book() { - super(); - } - - public Book(Long id, String name, String author) { - super(); - this.id = id; - this.name = name; - this.author = author; - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the author - */ - public String getAuthor() { - return author; - } - - /** - * @param author the author to set - */ - public void setAuthor(String author) { - this.author = author; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; - } + private Long id; + private String name; + private String author; + + @JsonInclude(NON_NULL) + private LocalDate pubDate; + @JsonInclude(NON_NULL) + private Date copyrightDate; + + public Book() { + super(); + } + + public Book(Long id, String name, String author) { + super(); + this.id = id; + this.name = name; + this.author = author; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the author + */ + public String getAuthor() { + return author; + } + + /** + * @param author + * the author to set + */ + public void setAuthor(String author) { + this.author = author; + } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; + } } diff --git a/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java new file mode 100644 index 0000000..0217794 --- /dev/null +++ b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java @@ -0,0 +1,81 @@ +package com.howtoprogram.gson; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.howtoprogram.jsonpojo.Book; + +public class GsonTest { + + @Test + public void testConvertOjectToJsonTest() { + Book milkHoneyBook = new Book(1000L, "Milk and Honey", "Rupi Kaur"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(milkHoneyBook); + + assertTrue(json.contains("Milk and Honey")); + System.out.print(json); + } + + @Test + public void testConvertListToJsonTest() { + Book sfBook = new Book(1001L, "StrengthsFinder 2.0", "Tom Rath"); + Book pHBook = new Book(1002L, "The Power of Habit", "Charles Duhigg"); + List books = new ArrayList(); + books.add(sfBook); + books.add(pHBook); + + // Converts the list to JSON + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(books); + assertTrue(json.contains("StrengthsFinder 2.0")); + assertTrue(json.contains("The Power of Habit")); + + System.out.println(json); + } + + @Test + public void testConvertSetToJsonTest() { + Book litteFireBook = new Book(1001L, "Little Fires Everywhere", "Celeste Ng"); + Book leoDaVinciBook = new Book(1002L, "Leonardo da Vinci", "Walter Isaacson"); + Set books = new HashSet(); + books.add(litteFireBook); + books.add(leoDaVinciBook); + + // Converts the set to JSON + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(books); + assertTrue(json.contains("Little Fires Everywhere")); + assertTrue(json.contains("Leonardo da Vinci")); + + System.out.println(json); + } + + @Test + public void testConvertMapToJsonTest() { + Book eoBook = new Book(1l, "Extreme Ownership", "Jocko Willink"); + Book lopBook = new Book(2l, "The 48 Laws of Power", "Robert Greene"); + Map booksMap = new HashMap(); + booksMap.put(eoBook.getId(), eoBook); + booksMap.put(lopBook.getId(), lopBook); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(booksMap); + + assertTrue(json.contains("Extreme Ownership")); + assertTrue(json.contains("The 48 Laws of Power")); + System.out.println(json); + } + +} diff --git a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java similarity index 58% rename from Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java rename to Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java index 6d736cd..04f2210 100644 --- a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java +++ b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java @@ -1,4 +1,7 @@ -package com.howtoprogram.jsonpojo; +package com.howtoprogram.gson; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; @@ -8,48 +11,36 @@ import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.howtoprogram.jsonpojo.Book; -public class JsonPojoUtils { - - public static void main(String[] args) { - // JSON to object - toObject(); - toList(); - toArray(); - - // Object to JSON - toJSON(); - collectionToJSON(); - // Working with file - serializeToFile(); - readFromFile(); - // collectionToJSONPrettyPrint(); - mapToJson(); - } +public class JacksonTest { /** * Converts a JSON string to a {@link Book} object + * + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException */ - public static void toObject() { + @Test + public void testConvertJsonToObject() throws Exception { String json = "{\"id\":2,\"name\":\"Thinking in Java\",\"author\":\"Bruce Eckel\"}"; // create Jackson ObjectMapper ObjectMapper mapper = new ObjectMapper(); - try { - // Converts JSON string to Java object - Book book = mapper.readValue(json, Book.class); - - System.out.println(book); - - } catch (JsonProcessingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } + // Converts JSON string to Java object + Book book = mapper.readValue(json, Book.class); + assertEquals(2, book.getId().longValue()); + assertEquals("Thinking in Java", book.getName()); + assertEquals("Bruce Eckel", book.getAuthor()); } /** @@ -113,63 +104,69 @@ public static void toJSON() { /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void mapToJson() { - Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); - Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); + @Test + public void convertMapToJsonTest() throws JsonProcessingException { + Book ilBook = new Book(1l, "The Immortalists", "Chloe Benjamin"); + Book gdrmBook = new Book(2l, "The Girl Who Drank the Moon", "Kelly Barnhill"); Map bookMap = new HashMap(); - bookMap.put(book1.getId(), book1); - bookMap.put(book2.getId(), book2); + bookMap.put(ilBook.getId(), ilBook); + bookMap.put(gdrmBook.getId(), gdrmBook); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookMap); - // json = mapper.writeValueAsString(bookMap); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookMap); + + assertTrue(json.contains(ilBook.getName())); + assertTrue(json.contains(gdrmBook.getName())); + + System.out.println(json); } /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void collectionToJSON() { - Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); - Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); + @Test + public void convertCollectionToJsonTest() throws JsonProcessingException { + Book h2prBook = new Book(1l, "Java How To Program", "Paul Deitel"); + Book thinkJavaBook = new Book(2l, "Thinking in Java", "Bruce Eckel"); List books = new ArrayList(); - books.add(book1); - books.add(book2); + books.add(h2prBook); + books.add(thinkJavaBook); + + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(books); + + assertTrue(json.contains(h2prBook.getName())); + assertTrue(json.contains(thinkJavaBook.getName())); + + System.out.println(json); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(books); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } } /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void collectionToJSONPrettyPrint() { + @Test + public void collectionToJSONPrettyPrintTest() throws JsonProcessingException { Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); List books = new ArrayList(); books.add(book1); books.add(book2); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); + System.out.println(json); + } /** @@ -198,6 +195,21 @@ public static void serializeToFile() { } } + @Test + public void testConvertObjectToJSON() throws JsonProcessingException { + Book shBook = new Book(1l, "Sour Heart", "Jenny Zhang"); + + // Converts the shBook to JSON + ObjectMapper mapper = new ObjectMapper(); + // String json = + // mapper.writerWithDefaultPrettyPrinter().writeValueAsString(shBook); + String json = mapper.writeValueAsString(shBook); + assertTrue(json.contains("Sour Heart")); + assertTrue(json.contains("Jenny Zhang")); + System.out.println(json); + + } + /** * Read JSON content from the file: d:/books.json and convert to an array. * Assume that the d:/books.json was exist. diff --git a/Java-RESTful-Client-Example/.classpath b/Java-RESTful-Client-Example/.classpath deleted file mode 100644 index 85b766f..0000000 --- a/Java-RESTful-Client-Example/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Java-RESTful-Client-Example/.gitignore b/Java-RESTful-Client-Example/.gitignore deleted file mode 100644 index b83d222..0000000 --- a/Java-RESTful-Client-Example/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/Java-RESTful-Client-Example/.project b/Java-RESTful-Client-Example/.project deleted file mode 100644 index f20c775..0000000 --- a/Java-RESTful-Client-Example/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - java-restful-client-example - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/Java-RESTful-Client-Example/.settings/org.eclipse.core.resources.prefs b/Java-RESTful-Client-Example/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 29abf99..0000000 --- a/Java-RESTful-Client-Example/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,6 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//src/test/java=UTF-8 -encoding//src/test/resources=UTF-8 -encoding/=UTF-8 diff --git a/Java-RESTful-Client-Example/.settings/org.eclipse.jdt.core.prefs b/Java-RESTful-Client-Example/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/Java-RESTful-Client-Example/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Java-RESTful-Client-Example/.settings/org.eclipse.m2e.core.prefs b/Java-RESTful-Client-Example/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/Java-RESTful-Client-Example/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/Java-RESTful-Client-Example/README.md b/Java-RESTful-Client-Example/README.md index 92a7324..ba00a44 100644 --- a/Java-RESTful-Client-Example/README.md +++ b/Java-RESTful-Client-Example/README.md @@ -33,13 +33,22 @@ The **BookResourceFeign.java, BookRepositoryImplFeign.java** includes all raw ex The **BookRepositoryImplUnirest.java** includes all raw examples about creating Java Java REST Client Using Unirest Java API Source code are described: -###[Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) -###[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) -###[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) -###[Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) -###[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) -###[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) -###[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) -###[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) -###[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) -###[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) \ No newline at end of file +### [Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) + +### [Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) + +### [Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) + +### [Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) + +### [Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) + +### [Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) + +### [Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) + +### [Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) + +### [Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) + +### [Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) diff --git a/README.md b/README.md index 4a6ee37..45ac6a1 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,36 @@ # Java Examples -## 1. Java JsonPojo Example +## 1.Java JsonPojo Example This small project contains examples how to convert Java object, Hashmap, List to JSON and vice versa. It also contains examples about how to work with files. -###[Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) -## 2. Book RESTful Service Examples +### [Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) +## 2.Book RESTful Service Examples This RESTful ws provides API for all below sub projects -## 3. Simple Java REST Client Example - -###[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) -###[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) -###[Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) -###[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) -###[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) -###[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) -###[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) -###[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) -###[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) -###[Java REST Client Examples Using OkHttp] (howtoprogram.xyz/2016/10/31/java-rest-client-examples-using-okhttp/) -###[How to Post with Retrofit 2] (http://howtoprogram.xyz/2017/02/17/how-to-post-with-retrofit-2/) -###[Ignore Unknown Properties or New Fields in Jackson] (http://howtoprogram.xyz/2017/02/18/ignore-exclude-new-fields-deserializing-jackson/) +## 3.Simple Java REST Client Example + +### [Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) + +### [Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) + +### [Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) + +### [Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) + +### [Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) + +### [Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) + +### [Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) + +### [Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) + +### [Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) + +### [Java REST Client Examples Using OkHttp](howtoprogram.xyz/2016/10/31/java-rest-client-examples-using-okhttp/) + +### [How to Post with Retrofit 2](http://howtoprogram.xyz/2017/02/17/how-to-post-with-retrofit-2/) + +### [Ignore Unknown Properties or New Fields in Jackson](http://howtoprogram.xyz/2017/02/18/ignore-exclude-new-fields-deserializing-jackson/) + + +## 4. Java 8 +### [Java 8 – Format Date, LocalDate, LocalDateTime and ZonedDateTime](https://howtoprogram.xyz/2017/08/20/java-8-format-date-localdate-localdatetime/) \ No newline at end of file diff --git a/feign-spring-cloud-example/README.md b/feign-spring-cloud-example/README.md index 3a7e191..1a8e059 100644 --- a/feign-spring-cloud-example/README.md +++ b/feign-spring-cloud-example/README.md @@ -20,4 +20,4 @@ Open spring-boot-netflix-feign-example\src\test\java\com\howtoprogram\Applicatio Right Click --> Run As --> JUnit test This RESTful ws provides API for all below sub projects: -###[howtoprogram.xyz/2017/01/29/using-netflix-feign-with-spring-cloud/]howtoprogram.xyz/2017/01/29/using-netflix-feign-with-spring-cloud/ \ No newline at end of file +### [howtoprogram.xyz/2017/01/29/using-netflix-feign-with-spring-cloud/]howtoprogram.xyz/2017/01/29/using-netflix-feign-with-spring-cloud/ \ No newline at end of file diff --git a/feign-spring-cloud-example/book-restful-service/.classpath b/feign-spring-cloud-example/book-restful-service/.classpath deleted file mode 100644 index af1430b..0000000 --- a/feign-spring-cloud-example/book-restful-service/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/feign-spring-cloud-example/book-restful-service/.project b/feign-spring-cloud-example/book-restful-service/.project deleted file mode 100644 index 2a0244f..0000000 --- a/feign-spring-cloud-example/book-restful-service/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - book-restful-service - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.core.resources.prefs b/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index e9441bb..0000000 --- a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding/=UTF-8 diff --git a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.jdt.core.prefs b/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.m2e.core.prefs b/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/feign-spring-cloud-example/book-restful-service/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/gson-examples/pom.xml b/gson-examples/pom.xml new file mode 100644 index 0000000..850cbc9 --- /dev/null +++ b/gson-examples/pom.xml @@ -0,0 +1,75 @@ + + 4.0.0 + com.howtoprogram + gson-examples + 0.0.1-SNAPSHOT + + + UTF-8 + 1.8 + 4.12 + 5.0.0 + ${junit.version}.0 + 5.0.0 + 1.0.0 + + + + + com.google.code.gson + gson + 2.8.2 + compile + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + junit + junit + ${junit.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + + + + + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19 + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + + \ No newline at end of file diff --git a/gson-examples/src/test/java/com/howtoprogram/gson/StringToJsonTest.java b/gson-examples/src/test/java/com/howtoprogram/gson/StringToJsonTest.java new file mode 100644 index 0000000..ef4cf32 --- /dev/null +++ b/gson-examples/src/test/java/com/howtoprogram/gson/StringToJsonTest.java @@ -0,0 +1,36 @@ +package com.howtoprogram.gson; + +import static org.junit.Assert.*; + +import com.google.gson.*; +import org.junit.Test; + +public class StringToJsonTest { + + @Test + public void testStringToJsonObject() { + + String json = "{\"id\":1,\"name\":\"Thinking in Java\",\"author\":\"Bruce Eckel\"}"; + JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject(); + + assertEquals(1, jsonObj.get("id").getAsInt()); + assertEquals("Thinking in Java", jsonObj.get("name").getAsString()); + assertEquals("Bruce Eckel", jsonObj.get("author").getAsString()); + + } + + @Test + public void testStringToJsonObjectWithJsonElement() { + + String json = "{\"id\":2,\"name\":\"Effective Java\",\"author\":\"Joshua Bloch\"}"; + + Gson gson = new Gson(); + JsonElement element = gson.fromJson(json, JsonElement.class); + JsonObject jsonObject = element.getAsJsonObject(); + + assertEquals(2, jsonObject.get("id").getAsInt()); + assertEquals("Effective Java", jsonObject.get("name").getAsString()); + assertEquals("Joshua Bloch", jsonObject.get("author").getAsString()); + + } +} diff --git a/java8-examples/pom.xml b/java8-examples/pom.xml new file mode 100644 index 0000000..dcef567 --- /dev/null +++ b/java8-examples/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + com.howtoprogram + java8-examples + 1.0-SNAPSHOT + + + + UTF-8 + 1.8 + 4.12 + + + + + + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + + + + + junit + junit + ${junit.version} + test + + + + + \ No newline at end of file diff --git a/java8-examples/src/test/java/Java8DateTimeTest.java b/java8-examples/src/test/java/Java8DateTimeTest.java new file mode 100644 index 0000000..2f3970d --- /dev/null +++ b/java8-examples/src/test/java/Java8DateTimeTest.java @@ -0,0 +1,86 @@ + + +import org.junit.Test; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import static org.junit.Assert.assertEquals; + +public class Java8DateTimeTest { + + @Test + public void testConvertLocalDateToDate() { + LocalDate localDate = LocalDate.of(2017, 8, 10); + + + Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + assertEquals(localDate.getYear(), calendar.get(Calendar.YEAR)); + assertEquals(localDate.getMonth().getValue(), calendar.get(Calendar.MONTH) + 1); + assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void testConvertLocalDateTimeToDate() { + LocalDateTime localDateTime = LocalDateTime.of(2017, 8, 10, 23, 10, 15); + + + Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + assertEquals(localDateTime.getYear(), calendar.get(Calendar.YEAR)); + assertEquals(localDateTime.getMonth().getValue(), calendar.get(Calendar.MONTH) + 1); + assertEquals(localDateTime.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void testConvertDateToLocalDate() { + + Calendar calendar = new GregorianCalendar(2017, Calendar.AUGUST, 20); + Date date = calendar.getTime(); + + + //Convert Date to LocalDate + LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone( + ZoneId.systemDefault()).toLocalDate(); + + + assertEquals(calendar.get(Calendar.YEAR), localDate.getYear()); + assertEquals(calendar.get(Calendar.MONTH) + 1, localDate.getMonth() + .getValue()); + assertEquals(calendar.get(Calendar.DAY_OF_MONTH), localDate.getDayOfMonth()); + + } + + @Test + public void testConvertDateToLocalDateTime() { + Calendar calendar = new GregorianCalendar(2017, Calendar.AUGUST, 20); + Date date = calendar.getTime(); + + + //Convert Date to LocalDateTime + LocalDateTime localDateTime = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId + .systemDefault()).toLocalDateTime(); + + + assertEquals(calendar.get(Calendar.YEAR), localDateTime.getYear()); + assertEquals(calendar.get(Calendar.MONTH) + 1, localDateTime.getMonth() + .getValue()); + assertEquals(calendar.get(Calendar.DAY_OF_MONTH), localDateTime.getDayOfMonth()); + assertEquals(calendar.get(Calendar.HOUR_OF_DAY), localDateTime.getHour()); + assertEquals(calendar.get(Calendar.MINUTE), localDateTime.getMinute()); + assertEquals(calendar.get(Calendar.SECOND), localDateTime.getSecond()); + + } +} diff --git a/java8-examples/src/test/java/Java8FormatDate.java b/java8-examples/src/test/java/Java8FormatDate.java new file mode 100644 index 0000000..8d4303c --- /dev/null +++ b/java8-examples/src/test/java/Java8FormatDate.java @@ -0,0 +1,154 @@ + + +import org.junit.Test; + +import java.text.SimpleDateFormat; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; + +import static java.time.format.DateTimeFormatter.*; +import static org.junit.Assert.assertEquals; + + +public class Java8FormatDate { + + @Test + public void testFormatDate() { + + //create a date object by using Calendar + Calendar calendar = new GregorianCalendar(2020, Calendar.AUGUST, 9); + Date date = calendar.getTime(); + + //create a pattern + String pattern = "dd/MM/yyyy"; + SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern); + // format the date + String olympicDate = dateFormatter.format(date); + //Validate + assertEquals("09/08/2020", olympicDate); + + } + + @Test + public void testFormatDateLongPattern() { + //create a date + int year = 2020; + int month = Calendar.AUGUST; + int day = 9; + int hourOfDay = 23; + int minute = 59; + int second = 59; + Calendar calendar = new GregorianCalendar(year, month, day, hourOfDay, + minute, second); + + Date date = calendar.getTime(); + + //create a long pattern with en_US locale + String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSS"; + SimpleDateFormat dateFormatter = + new SimpleDateFormat(pattern, new Locale("en", "US")); + + //format the date + String olympicDate = dateFormatter.format(date); + + //validate + assertEquals("Sunday August 2020 23:59:59.000", olympicDate); + + } + @Test + public void testFormatLocalDate() { + + //create a LocalDate object + LocalDate date = LocalDate.of(2020, Month.AUGUST, 9); + + //create a pattern + String pattern = "dd/MM/yyyy"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + + // format the date + String olympicDate = formatter.format(date); + + //Validate + assertEquals("09/08/2020", olympicDate); + + } + @Test + public void testFormatLocalDateUsingPreDefinedFormatter() { + + //create a LocalDate object + LocalDate date = LocalDate.of(2020, Month.AUGUST, 9); + + // format the date + String olympicDate = ISO_DATE.format(date); + assertEquals("2020-08-09", olympicDate); + + //or use as a pattern + olympicDate = date.format(ISO_DATE); + assertEquals("2020-08-09", olympicDate); + + } + @Test + public void testFormatLocalDateTime() { + + //create a LocalDate object + LocalDateTime dt = LocalDateTime.of(2020, Month.AUGUST, 9, 23, 59, 59); + + //create a pattern + String pattern = "yyyy/MM/dd HH:mm:ss"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + + // format the date + String olympicDate = formatter.format(dt); + assertEquals("2020/08/09 23:59:59", olympicDate); + + } + @Test + public void testFormatLocalDateTimeUsingPreDefinedFormatters() { + + //create a LocalDate object + LocalDateTime dt = LocalDateTime.of(2020, Month.AUGUST, 9, 23, 59, 59); + + // format the date + String olympicDate = ISO_LOCAL_DATE_TIME.format(dt); + assertEquals("2020-08-09T23:59:59", olympicDate); + + // or using as a pattern + olympicDate = dt.format(ISO_LOCAL_DATE_TIME); + assertEquals("2020-08-09T23:59:59", olympicDate); + + } + + @Test + public void testFormatZonedDateTime() { + + //create a LocalDate object + LocalDateTime dt = LocalDateTime.of(2020, Month.AUGUST, 9, 23, 59, 59); + ZonedDateTime japanZonedDT = ZonedDateTime.of(dt, ZoneId.of("Asia/Tokyo")); + // format the date + String pattern = "yyyy/MM/dd HH:mm:ssXXX"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + + String olympicDate = formatter.format(japanZonedDT); + assertEquals("2020/08/09 23:59:59+09:00", olympicDate); + + } + @Test + public void testFormatZonedDateTimeUsingPreDefinedFormatters() { + + //create a LocalDate object + LocalDateTime dt = LocalDateTime.of(2020, Month.AUGUST, 9, 23, 59, 59); + ZonedDateTime japanZonedDT = ZonedDateTime.of(dt, ZoneId.of("Asia/Tokyo")); + // format the date + String olympicDate = ISO_OFFSET_DATE_TIME.format(japanZonedDT); + assertEquals("2020-08-09T23:59:59+09:00", olympicDate); + + // or using as a pattern + olympicDate = japanZonedDT.format(ISO_OFFSET_DATE_TIME); + assertEquals("2020-08-09T23:59:59+09:00", olympicDate); + + } +} diff --git a/okhttp-examples/.classpath b/okhttp-examples/.classpath deleted file mode 100644 index 0a1dadd..0000000 --- a/okhttp-examples/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/okhttp-examples/.gitignore b/okhttp-examples/.gitignore deleted file mode 100644 index 66be49f..0000000 --- a/okhttp-examples/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/target/ -/.settings/ -/.classpath/ -/.project/ \ No newline at end of file diff --git a/okhttp-examples/.project b/okhttp-examples/.project deleted file mode 100644 index 8c3fbfc..0000000 --- a/okhttp-examples/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - okhttp-examples - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/open-feign-example/.classpath b/open-feign-example/.classpath deleted file mode 100644 index c6b4bf6..0000000 --- a/open-feign-example/.classpath +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/open-feign-example/.gitignore b/open-feign-example/.gitignore deleted file mode 100644 index b776fb7..0000000 --- a/open-feign-example/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -/target/ -/.idea/ -/.settings/ -/.project/ -/.classpath/ -/open-feign-example.iml \ No newline at end of file diff --git a/open-feign-example/.project b/open-feign-example/.project deleted file mode 100644 index cb590b8..0000000 --- a/open-feign-example/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - open-feign-example - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/open-feign-example/.settings/org.eclipse.core.resources.prefs b/open-feign-example/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 29abf99..0000000 --- a/open-feign-example/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,6 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//src/test/java=UTF-8 -encoding//src/test/resources=UTF-8 -encoding/=UTF-8 diff --git a/open-feign-example/.settings/org.eclipse.jdt.core.prefs b/open-feign-example/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/open-feign-example/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/open-feign-example/.settings/org.eclipse.m2e.core.prefs b/open-feign-example/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/open-feign-example/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/open-feign-example/README.md b/open-feign-example/README.md index 5ab9407..bf8ea27 100644 --- a/open-feign-example/README.md +++ b/open-feign-example/README.md @@ -10,5 +10,6 @@ Click **Finish** button to finish the importing Source code are described in: -###[File Uploading with Open Feign](http://howtoprogram.xyz/2016/12/29/file-uploading-open-feign/) -###[Basic Authentication with Open Feign](http://howtoprogram.xyz/2016/11/22/basic-authentication-open-feign/) \ No newline at end of file +### [File Uploading with Open Feign](http://howtoprogram.xyz/2016/12/29/file-uploading-open-feign/) + +### [Basic Authentication with Open Feign](http://howtoprogram.xyz/2016/11/22/basic-authentication-open-feign/) diff --git a/retrofit-post-json/pom.xml b/retrofit-post-json/pom.xml new file mode 100644 index 0000000..53ecfc1 --- /dev/null +++ b/retrofit-post-json/pom.xml @@ -0,0 +1,38 @@ + + 4.0.0 + com.howtoprogram + retrofit-post-json + 0.0.1-SNAPSHOT + jar + + retrofit-post-json + https://howtoprogram.xyz/2017/12/30/retrofit-post-json/ + + + UTF-8 + 1.8 + 1.8 + + + + + + + + com.squareup.retrofit2 + retrofit + 2.3.0 + + + com.squareup.retrofit2 + converter-gson + 2.3.0 + + + junit + junit + 4.12 + + + diff --git a/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/Book.java b/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/Book.java new file mode 100644 index 0000000..c38f119 --- /dev/null +++ b/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/Book.java @@ -0,0 +1,76 @@ +package com.howtoprogram.retrofit2; + +import javax.xml.bind.annotation.XmlRootElement; + +public class Book { + + private Long id; + private String name; + private String author; + + public Book() { + + } + // getter and sett + + + public Book(Long id, String name, String author) { + super(); + this.id = id; + this.name = name; + this.author = author; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the author + */ + public String getAuthor() { + return author; + } + + /** + * @param author the author to set + */ + public void setAuthor(String author) { + this.author = author; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; + } + +} diff --git a/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/BookResource.java b/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/BookResource.java new file mode 100644 index 0000000..7566db8 --- /dev/null +++ b/retrofit-post-json/src/main/java/com/howtoprogram/retrofit2/BookResource.java @@ -0,0 +1,23 @@ +package com.howtoprogram.retrofit2; + + +import okhttp3.MultipartBody; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.http.*; + +import java.util.HashMap; +import java.util.Map; + +public interface BookResource { + + + @POST("books") + Call createBook(@Body Book book); + + @POST("books") + Call updateBook(@Body Map body); + +} diff --git a/retrofit-post-json/src/test/java/com/howtoprogram/retrofit2/BookResourceTest.java b/retrofit-post-json/src/test/java/com/howtoprogram/retrofit2/BookResourceTest.java new file mode 100644 index 0000000..d1378ed --- /dev/null +++ b/retrofit-post-json/src/test/java/com/howtoprogram/retrofit2/BookResourceTest.java @@ -0,0 +1,59 @@ +package com.howtoprogram.retrofit2; + +import org.junit.Test; +import retrofit2.Call; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; + +public class BookResourceTest { + + @Test + public void testPostJsonByPojo() throws IOException { + + //create an instance of Retrofit + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("http://localhost:8080/v1/") + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + //create an instance of the BookResource interface + BookResource bookResource = retrofit.create(BookResource.class); + //create a Book object + Book book = new Book(1l, "Java How To Program", "Paul Deitel"); + + // send the Book to the Rest API + Call call = bookResource.createBook(book); + Response response = call.execute(); + + assertTrue(response.isSuccessful()); + + } + + @Test + public void testPostJsonByMap() throws IOException { + + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("http://localhost:8080/v1/") + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + BookResource bookResource = retrofit.create(BookResource.class); + Map bookMap = new HashMap<>(); + bookMap.put("name", "To Kill a Mockingbird"); + bookMap.put("author", "Harper Lee"); + + Call call = bookResource.updateBook(bookMap); + Response response = call.execute(); + + assertTrue(response.isSuccessful()); + + } + +} diff --git a/rxjava2-examples/pom.xml b/rxjava2-examples/pom.xml new file mode 100644 index 0000000..f75a959 --- /dev/null +++ b/rxjava2-examples/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + com.howtoprogram + rxjava2-examples + 0.0.1-SNAPSHOT + + + UTF-8 + 1.8 + 4.12 + 5.0.0 + ${junit.version}.0 + 5.0.0 + 1.0.0 + + + + + io.reactivex.rxjava2 + rxjava + 2.1.8 + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + junit + junit + ${junit.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + + + + + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19 + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + + \ No newline at end of file diff --git a/rxjava2-examples/src/test/java/com/howtoprogram/rxjava2/RxJavaFlatMapTest.java b/rxjava2-examples/src/test/java/com/howtoprogram/rxjava2/RxJavaFlatMapTest.java new file mode 100644 index 0000000..b9585a4 --- /dev/null +++ b/rxjava2-examples/src/test/java/com/howtoprogram/rxjava2/RxJavaFlatMapTest.java @@ -0,0 +1,67 @@ +package com.howtoprogram.rxjava2; + +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.functions.Consumer; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class RxJavaFlatMapTest { + + @Test + public void flatMapObservableTest() { + + List sentences = new ArrayList<>(); + sentences.add("Ladybug! Ladybug!"); + sentences.add("Fly away home."); + sentences.add("Your house is on fire."); + sentences.add("And your children all gone."); + + Observable.fromIterable(sentences) + .flatMap(s -> Observable.fromArray(s.split(" "))) + .blockingSubscribe(System.out::println); + +// Observable.fromIterable(sentences) +// .flatMap(s -> Observable.fromArray(s.split(" ")), (s1, s2) -> findOccurrences(s1, s2)) +// .blockingSubscribe(System.out::println); + + } + @Test + public void flatMapFlowableTest() { + + List sentences = new ArrayList<>(); + sentences.add("Fly away home."); + sentences.add("One plus one, two for life"); + sentences.add("Over and over again"); + + Flowable.fromIterable(sentences) + .flatMap(s -> Flowable.fromArray(s.split(" "))) + .blockingSubscribe(System.out::println); + + +// Flowable.fromIterable(sentences) +// .flatMap(s -> Flowable.fromArray(s.split(" ")), (s1, s2) -> findOccurrences(s1, s2)) +// .blockingSubscribe(System.out::println); + + } + + private static String findOccurrences(String str, String findStr) { + + int lastIndex = 0; + int count = 0; + + while (lastIndex != -1) { + + lastIndex = str.indexOf(findStr, lastIndex); + + if (lastIndex != -1) { + count++; + lastIndex += findStr.length(); + } + } + return String.format("'%s' appears %d times in '%s' ", findStr, count, str); + } + +} diff --git a/spring-new-reqmapping-annotations/.classpath b/spring-new-reqmapping-annotations/.classpath deleted file mode 100644 index af1430b..0000000 --- a/spring-new-reqmapping-annotations/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-new-reqmapping-annotations/.project b/spring-new-reqmapping-annotations/.project deleted file mode 100644 index 43874da..0000000 --- a/spring-new-reqmapping-annotations/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - spring-new-reqmapping-annotations - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/spring-new-reqmapping-annotations/.settings/org.eclipse.core.resources.prefs b/spring-new-reqmapping-annotations/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index e9441bb..0000000 --- a/spring-new-reqmapping-annotations/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding/=UTF-8 diff --git a/spring-new-reqmapping-annotations/.settings/org.eclipse.jdt.core.prefs b/spring-new-reqmapping-annotations/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/spring-new-reqmapping-annotations/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-new-reqmapping-annotations/.settings/org.eclipse.m2e.core.prefs b/spring-new-reqmapping-annotations/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/spring-new-reqmapping-annotations/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-new-reqmapping-annotations/README.md b/spring-new-reqmapping-annotations/README.md index 5e72e3a..3cb45a8 100644 --- a/spring-new-reqmapping-annotations/README.md +++ b/spring-new-reqmapping-annotations/README.md @@ -16,4 +16,4 @@ Open the **Application.java** **Right click -> Run As -> Java Application** or use the shortcut: **Alt+Shift+x, j** to start the main method -###[Using New Composed Annotations for @RequestMapping in Spring Framework](http://howtoprogram.xyz/2017/03/16/using-new-composed-annotations-of-requestmapping-in-spring-framework/) \ No newline at end of file +### [Using New Composed Annotations for @RequestMapping in Spring Framework](http://howtoprogram.xyz/2017/03/16/using-new-composed-annotations-of-requestmapping-in-spring-framework/) \ No newline at end of file diff --git a/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.jar b/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..5fd4d50 Binary files /dev/null and b/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.properties b/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c954cec --- /dev/null +++ b/springboot-jackson-java8date/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip diff --git a/springboot-jackson-java8date/build.gradle b/springboot-jackson-java8date/build.gradle new file mode 100644 index 0000000..c9c11c9 --- /dev/null +++ b/springboot-jackson-java8date/build.gradle @@ -0,0 +1,32 @@ +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE") + } +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'org.springframework.boot' + +jar { + baseName = 'gs-rest-service' + version = '0.1.0' +} + +repositories { + mavenCentral() +} + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web") + testCompile('org.springframework.boot:spring-boot-starter-test') + testCompile('com.jayway.jsonpath:json-path') +} + diff --git a/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.jar b/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..05ef575 Binary files /dev/null and b/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.jar differ diff --git a/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.properties b/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a4b2554 --- /dev/null +++ b/springboot-jackson-java8date/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Aug 29 13:08:10 CDT 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip diff --git a/springboot-jackson-java8date/gradlew b/springboot-jackson-java8date/gradlew new file mode 100644 index 0000000..9d82f78 --- /dev/null +++ b/springboot-jackson-java8date/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/springboot-jackson-java8date/gradlew.bat b/springboot-jackson-java8date/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/springboot-jackson-java8date/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/Book-RESTful-Service/manifest.yml b/springboot-jackson-java8date/manifest.yml similarity index 100% rename from Book-RESTful-Service/manifest.yml rename to springboot-jackson-java8date/manifest.yml diff --git a/springboot-jackson-java8date/mvnw b/springboot-jackson-java8date/mvnw new file mode 100644 index 0000000..a1ba1bf --- /dev/null +++ b/springboot-jackson-java8date/mvnw @@ -0,0 +1,233 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} "$@" diff --git a/springboot-jackson-java8date/mvnw.cmd b/springboot-jackson-java8date/mvnw.cmd new file mode 100644 index 0000000..2b934e8 --- /dev/null +++ b/springboot-jackson-java8date/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% \ No newline at end of file diff --git a/springboot-jackson-java8date/pom.xml b/springboot-jackson-java8date/pom.xml new file mode 100644 index 0000000..42fb689 --- /dev/null +++ b/springboot-jackson-java8date/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.howtoprogram + springboot-jackson-java8date + 0.1.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.5.9.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.springframework.boot + spring-boot-starter-test + test + + + com.jayway.jsonpath + json-path + test + + + + + 1.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/springboot-jackson-java8date/src/main/java/hello/Application.java b/springboot-jackson-java8date/src/main/java/hello/Application.java new file mode 100644 index 0000000..5abd411 --- /dev/null +++ b/springboot-jackson-java8date/src/main/java/hello/Application.java @@ -0,0 +1,12 @@ +package hello; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/springboot-jackson-java8date/src/main/java/hello/Member.java b/springboot-jackson-java8date/src/main/java/hello/Member.java new file mode 100644 index 0000000..15d820a --- /dev/null +++ b/springboot-jackson-java8date/src/main/java/hello/Member.java @@ -0,0 +1,56 @@ +package hello; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Member { + + private Long id; + private String firstName; + private String lastName; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + private LocalDate birthDate; + private LocalDateTime registeredDateTime; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public LocalDate getBirthDate() { + return birthDate; + } + + public void setBirthDate(LocalDate birthDate) { + this.birthDate = birthDate; + } + + public LocalDateTime getRegisteredDateTime() { + return registeredDateTime; + } + + public void setRegisteredDateTime(LocalDateTime registeredDateTime) { + this.registeredDateTime = registeredDateTime; + } +} diff --git a/springboot-jackson-java8date/src/main/java/hello/MemberController.java b/springboot-jackson-java8date/src/main/java/hello/MemberController.java new file mode 100644 index 0000000..96f5d23 --- /dev/null +++ b/springboot-jackson-java8date/src/main/java/hello/MemberController.java @@ -0,0 +1,32 @@ +package hello; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Month; +import java.util.concurrent.atomic.AtomicLong; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MemberController { + + private static final String template = "Hello, %s!"; + private final AtomicLong counter = new AtomicLong(); + + @RequestMapping("/member") + public Member getDefaultMember() { + Member member = new Member(); + member.setId(1L); + member.setFirstName("Tom"); + member.setLastName("Sawyer"); + member.setBirthDate(LocalDate.of(2001, Month.APRIL, 20)); + member.setRegisteredDateTime(LocalDateTime.of( + 2017, Month.JUNE, 29, 20, 40, 59)); + + return member; + } +} diff --git a/springboot-jackson-java8date/src/main/resources/application.properties b/springboot-jackson-java8date/src/main/resources/application.properties new file mode 100644 index 0000000..f7abf52 --- /dev/null +++ b/springboot-jackson-java8date/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.jackson.serialization.write-dates-as-timestamps=false \ No newline at end of file diff --git a/springboot-jackson-java8date/src/test/java/hello/MemberControllerTests.java b/springboot-jackson-java8date/src/test/java/hello/MemberControllerTests.java new file mode 100644 index 0000000..47a770a --- /dev/null +++ b/springboot-jackson-java8date/src/test/java/hello/MemberControllerTests.java @@ -0,0 +1,89 @@ +/* + * Copyright 2016 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 hello; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Month; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class MemberControllerTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void getMemberTest() throws Exception { + + this.mockMvc.perform(get("/member")).andDo(print()).andExpect(status().isOk()) + .andExpect(jsonPath("$.birthDate").value("2001-04-20")); + } + @Test + public void testJava8DateTimeJacksonDefault() throws JsonProcessingException { + Member member = new Member(); + member.setId(1L); + member.setFirstName("Tom"); + member.setLastName("Sawyer"); + member.setBirthDate(LocalDate.of(2001, Month.APRIL, 20)); + member.setRegisteredDateTime(LocalDateTime.of( + 2017, Month.JUNE, 29, 20, 40, 59)); + + ObjectMapper objectMapper = new ObjectMapper(); + + System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(member)); + + } + + @Test + public void testJava8DateTimeJacksonJsr310() throws JsonProcessingException { + Member member = new Member(); + member.setId(1L); + member.setFirstName("Tom"); + member.setLastName("Sawyer"); + member.setBirthDate(LocalDate.of(2001, Month.APRIL, 20)); + member.setRegisteredDateTime(LocalDateTime.of( + 2017, Month.JUNE, 29, 20, 40, 59)); + + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + + System.out.println(objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(member)); + + } + +} diff --git a/unirest-java-examples/README.md b/unirest-java-examples/README.md new file mode 100644 index 0000000..af27e7f --- /dev/null +++ b/unirest-java-examples/README.md @@ -0,0 +1,16 @@ +# Unirest for Java Example and Tutorials + + +## 1. Import source code into Eclipse + +Menu **File –> Import –> Maven –> Existing Maven Projects** + +Browse to your source code location + +Click **Finish** button to finish the importing + + +Source code are described: +### [Configure Basic Authentication on Unirest for Java](https://howtoprogram.xyz/2017/08/19/configure-basic-authentication-unirest-java/) + +### [Java REST Client Example](https://howtoprogram.xyz/java-technologies/java-rest-client-example/) diff --git a/unirest-java-examples/pom.xml b/unirest-java-examples/pom.xml new file mode 100644 index 0000000..c5b61b2 --- /dev/null +++ b/unirest-java-examples/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + com.howtoprogram.unirest + unirest-java-examples + 0.0.1-SNAPSHOT + jar + + Unirest Java Examples and Tutorials + http://maven.apache.org + + + UTF-8 + 1.8 + 1.8 + + + + + com.mashape.unirest + unirest-java + 1.4.9 + + + commons-io + commons-io + 2.5 + test + + + junit + junit + 4.12 + + + diff --git a/unirest-java-examples/src/test/java/com/howtoprogram/BasicAuthenticationTest.java b/unirest-java-examples/src/test/java/com/howtoprogram/BasicAuthenticationTest.java new file mode 100644 index 0000000..789d176 --- /dev/null +++ b/unirest-java-examples/src/test/java/com/howtoprogram/BasicAuthenticationTest.java @@ -0,0 +1,40 @@ +package com.howtoprogram; + + +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.exceptions.UnirestException; +import com.mashape.unirest.http.utils.Base64Coder; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.*; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + +public class BasicAuthenticationTest { + + @Test + public void testBasicAuthAPI() throws IOException, UnirestException { + + HttpResponse response = Unirest.get("http://httpbin.org/basic-auth/user/passwd") + .basicAuth("user", "passwd") + .asJson(); + assertThat(response.getStatus(), equalTo(200)); + } + + @Test + public void testBasicAuthRawHeader() throws IOException, UnirestException { + + HttpResponse response = Unirest.get("http://httpbin.org/basic-auth/user/passwd"). + header("Authorization", "Basic " + Base64Coder.encodeString("user" + ":" + "passwd")) + .asJson(); + + assertThat(response.getStatus(), equalTo(200)); + } +} diff --git a/unirest-java-examples/src/test/java/com/howtoprogram/UnirestIntroductionTest.java b/unirest-java-examples/src/test/java/com/howtoprogram/UnirestIntroductionTest.java new file mode 100644 index 0000000..9c096bc --- /dev/null +++ b/unirest-java-examples/src/test/java/com/howtoprogram/UnirestIntroductionTest.java @@ -0,0 +1,66 @@ +package com.howtoprogram; + +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.async.Callback; +import com.mashape.unirest.http.exceptions.UnirestException; +import static org.junit.Assert.*; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.concurrent.Future; + +/** + * Created by nangs on 12/31/2016. + */ +public class UnirestIntroductionTest { + private static final String BASE_URL = "http://httpbin.org/get"; + + + @Test + public void getWithParameters() throws IOException, UnirestException { + HttpResponse response = Unirest.get(BASE_URL).queryString("username", "admin").asJson(); + assertTrue(response.getStatus()==200); + + } + + @Test + public void getWithParametersVal() throws IOException, UnirestException { + HttpResponse response = Unirest.get(BASE_URL).queryString("username", "admin").asJson(); + String value = response.getBody().getObject().getJSONObject("args").get("username").toString(); + assertEquals(value,"admin"); + + } + + @Test + public void getASynchronously() throws IOException { + Future> future = Unirest.get(BASE_URL).queryString("username", "admin") + .header("accept", "application/json") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail("The request has failed"); + } + + public void completed(HttpResponse response) { + assertTrue(response.getStatus()==200); + } + + public void cancelled() { + fail("The test is cancelled"); + } + + }); + } + @Test + public void postWithUnirest() throws IOException, UnirestException { + HttpResponse response = Unirest.get(BASE_URL).queryString("username", "admin").asJson(); + String value = response.getBody().getObject().getJSONObject("args").get("username").toString(); + assertEquals(value,"admin"); + + } + +}