├── .gitignore ├── LICENSE ├── README.md ├── archive ├── java-9 │ ├── coin │ │ └── Main.java │ ├── http2 │ │ ├── Main.java │ │ └── README.md │ ├── jigsaw │ │ ├── README.md │ │ └── src │ │ │ ├── com.greetings │ │ │ ├── com │ │ │ │ └── greetings │ │ │ │ │ └── Main.java │ │ │ └── module-info.java │ │ │ └── org.astro │ │ │ ├── module-info.java │ │ │ └── org │ │ │ └── astro │ │ │ └── DefaultAstroHelloWorldNameMessageStringProvider.java │ ├── lists │ │ └── Lists.java │ ├── mrjar │ │ ├── MANIFEST.MF │ │ ├── README.md │ │ └── src │ │ │ └── main │ │ │ ├── java-9 │ │ │ └── Generator.java │ │ │ └── java │ │ │ ├── Application.java │ │ │ └── Generator.java │ ├── process │ │ └── Main.java │ └── repl │ │ ├── README.md │ │ ├── bash.jsh │ │ ├── guava-test.jsh │ │ └── hello.jsh ├── java14 │ ├── DemoPatternMatching.java │ ├── DemoSwitch.java │ ├── DemoTextBlocks.java │ ├── FlightRecorderDemo.java │ └── books.xml └── lvti │ └── Main.java ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── org │ └── thinkbigthings │ └── demo │ ├── httpclient │ └── Main.java │ └── records │ ├── BuildablePerson.java │ ├── CheckedFunction.java │ ├── Expression.java │ ├── Functional.java │ ├── Try.java │ └── jpa │ ├── Store.java │ ├── StoreRecord.java │ └── StoreRepository.java └── test └── java └── org └── thinkbigthings └── demo ├── gatherers ├── FunctionalFinders.java └── GathererTest.java └── records ├── BasicTest.java ├── BuilderTest.java ├── DtoTest.java ├── JpaTest.java ├── MapKeyTest.java ├── MultiReturnTest.java ├── StreamTest.java └── TreeNodeTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | build/ 4 | out/ 5 | 6 | # Log file 7 | *.log 8 | 9 | # gradle 10 | .gradle/ 11 | 12 | # intellij files 13 | *.iml 14 | .idea/ 15 | 16 | # Package Files # 17 | *.jar 18 | *.war 19 | *.nar 20 | *.ear 21 | *.zip 22 | *.tar.gz 23 | *.rar 24 | 25 | # Allow gradle wrapper 26 | !gradle/wrapper/gradle-wrapper.jar 27 | 28 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 29 | hs_err_pid* 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Features 2 | 3 | Demonstrate Java language features and other experimental items. 4 | 5 | gradlew wrapper --gradle-version 8.10.1 --distribution-type all 6 | 7 | -------------------------------------------------------------------------------- /archive/java-9/coin/Main.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) throws Exception { 8 | 9 | // Coin 1: resources may be declared outside the try statement (if effectively final) 10 | BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("Main.java"))); 11 | List lines = new ArrayList<>(); 12 | try(reader) { 13 | reader.lines().forEach(lines::add); 14 | } 15 | catch(Exception ex) { 16 | // Never swallow exceptions, right? 17 | } 18 | 19 | ListProcessor processor = new ListProcessor() {}; 20 | 21 | int numOriginal = lines.size(); 22 | int numFlat = processor.flatten(lines).size(); 23 | System.out.println("number of duplicate lines: " + (numOriginal - numFlat)); 24 | } 25 | 26 | interface ListProcessor { 27 | 28 | default List flatten(List... lists) { 29 | return flattenStrings(lists); 30 | } 31 | 32 | // Coin 2: @SafeVarargs can now be put on private methods (formerly only static or final) 33 | // Coin 3: interfaces can now have private methods (no ambiguity if extending with same method) 34 | @SafeVarargs 35 | private List flattenStrings(List... lists) { 36 | 37 | // Coin 4: anonymous classes can now use inference for generic types 38 | // Coin 5: single underscore can NO LONGER be used as variable name 39 | Set _strings = new HashSet<>(){}; 40 | for(List list : lists) { 41 | _strings.addAll(list); 42 | } 43 | return new ArrayList<>(_strings); 44 | } 45 | 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /archive/java-9/http2/Main.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | import jdk.incubator.http.*; 4 | import java.net.URI; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | 8 | import static jdk.incubator.http.HttpRequest.*; 9 | import static jdk.incubator.http.HttpResponse.*; 10 | import static java.nio.charset.StandardCharsets.*; 11 | 12 | public class Main { 13 | 14 | public static void main(String[] args) throws Exception { 15 | 16 | String stackOverflow = "https://stackoverflow.com"; 17 | requestStreaming(stackOverflow); 18 | // requestSync(stackOverflow); 19 | 20 | System.out.println("Program done."); 21 | System.exit(0); 22 | } 23 | 24 | public static void requestSync(String url) throws Exception { 25 | 26 | // clients are immutable and thread safe 27 | HttpClient client = HttpClient.newHttpClient(); 28 | 29 | // GET 30 | HttpResponse response = client.send( 31 | HttpRequest 32 | .newBuilder(new URI(url)) 33 | .GET() 34 | .build(), 35 | BodyHandler.asString() 36 | ); 37 | 38 | int statusCode = response.statusCode(); 39 | processResponseBody(response.body()); 40 | } 41 | 42 | public static void requestStreaming(String url) throws Exception { 43 | 44 | HttpClient client = HttpClient.newHttpClient(); 45 | 46 | CompletableFuture> response = client.sendAsync( 47 | HttpRequest 48 | .newBuilder(new URI(url)) 49 | .GET() 50 | .build(), 51 | BodyHandler.asString() 52 | ); 53 | 54 | response.thenAccept( s -> processResponseBody(s.body())).join(); 55 | } 56 | 57 | public static void processResponseBody(String body) { 58 | processResponseBody(new ByteArrayInputStream(body.getBytes(UTF_8))); 59 | } 60 | 61 | public static void processResponseBody(InputStream stream) { 62 | 63 | try(BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) { 64 | br.lines().forEach(Main::processLine); 65 | } 66 | catch(Exception e) { 67 | e.printStackTrace(); 68 | } 69 | System.out.println("Processing Done!"); 70 | } 71 | 72 | public static void processLine(String line) { 73 | System.out.print("."); 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /archive/java-9/http2/README.md: -------------------------------------------------------------------------------- 1 | 2 | // javadoc is available at 3 | https://docs.oracle.com/javase/9/docs/api/jdk/incubator/http/HttpClient.html 4 | 5 | // to run with the incubator module, need to explicitly add it 6 | javac --add-modules jdk.incubator.httpclient Main.java 7 | java --add-modules jdk.incubator.httpclient Main 8 | 9 | -------------------------------------------------------------------------------- /archive/java-9/jigsaw/README.md: -------------------------------------------------------------------------------- 1 | 2 | project based on the example in http://openjdk.java.net/projects/jigsaw/quick-start 3 | 4 | // reset 5 | rm -rf greetingsapp mlib mods 6 | 7 | // Build multiple modules 8 | javac -d mods --module-source-path src $(find src -name "*.java") 9 | 10 | // Run module (specify module path and module name) 11 | java --module-path mods -m com.greetings/com.greetings.Main 12 | 13 | // Package as modular jars (a regular JAR file that has a module-info.class) 14 | mkdir mlib 15 | jar --create --file=mlib/org.astro-1.0.jar --module-version=1.0 -C mods/org.astro . 16 | jar --create --file=mlib/com.greetings.jar --main-class=com.greetings.Main -C mods/com.greetings . 17 | ls mlib 18 | 19 | // Run module directly (like java -jar) 20 | java -p mlib -m com.greetings 21 | 22 | // create modular runtime image with my modules 23 | // jlink --module-path $JAVA_HOME/jmods:mlib --add-modules com.greetings --output greetingsapp 24 | jlink --strip-debug --compress=2 --module-path $JAVA_HOME/jmods:mlib --add-modules com.greetings --launcher hello=com.greetings/com.greetings.Main --output greetingsapp 25 | 26 | // how big is it? 27 | du -h greetingsapp/ 28 | 29 | // run it as a java application 30 | greetingsapp/bin/java -m com.greetings 31 | 32 | // or run the launch command (from --launcher) 33 | greetingsapp/bin/hello 34 | 35 | // edit relevant files at once: 36 | gedit src/com.greetings/com/greetings/Main.java src/org.astro/org/astro/DefaultAstroHelloWorldNameMessageStringProvider.java src/com.greetings/module-info.java src/org.astro/module-info.java README.md & 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /archive/java-9/jigsaw/src/com.greetings/com/greetings/Main.java: -------------------------------------------------------------------------------- 1 | package com.greetings; 2 | 3 | // simple and easy to remember 4 | import org.astro.DefaultAstroHelloWorldNameMessageStringProvider; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | System.out.format("Greetings %s!%n", DefaultAstroHelloWorldNameMessageStringProvider.name()); 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /archive/java-9/jigsaw/src/com.greetings/module-info.java: -------------------------------------------------------------------------------- 1 | module com.greetings { 2 | // module we depend on 3 | requires org.astro; 4 | } 5 | -------------------------------------------------------------------------------- /archive/java-9/jigsaw/src/org.astro/module-info.java: -------------------------------------------------------------------------------- 1 | module org.astro { 2 | // package we export 3 | exports org.astro; 4 | } 5 | -------------------------------------------------------------------------------- /archive/java-9/jigsaw/src/org.astro/org/astro/DefaultAstroHelloWorldNameMessageStringProvider.java: -------------------------------------------------------------------------------- 1 | package org.astro; 2 | 3 | public class DefaultAstroHelloWorldNameMessageStringProvider { 4 | public static String name() { 5 | return "world"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /archive/java-9/lists/Lists.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.IOException; 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | import java.util.Set; 6 | import java.util.HashSet; 7 | import java.util.Collections; 8 | import java.util.stream.Stream; 9 | 10 | import static java.util.stream.Collectors.toSet; 11 | 12 | public class Lists { 13 | 14 | public static void main(String[] args) throws IOException { 15 | 16 | List> stringList = new ArrayList<>(); 17 | for(int i=0; i < 100; i++) { 18 | Generator gen = new Generator(); 19 | stringList.add(gen.createStringsJava9()); 20 | } 21 | 22 | System.out.print("press Enter to continue:"); 23 | System.in.read(); 24 | } 25 | 26 | public static class Generator { 27 | 28 | private byte[] lotsOfHiddenStuff = new byte[5_000_000]; 29 | 30 | public Set createStringsJava9() { 31 | return Set.of("Java", "9"); 32 | } 33 | 34 | public Set createStringsJava8() { 35 | return Collections.unmodifiableSet(Stream.of("Java", "8").collect(toSet())); 36 | } 37 | 38 | public Set createStringsJava7() { 39 | Set strings = new HashSet(); 40 | strings.add("Java"); 41 | strings.add("7"); 42 | return strings; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /archive/java-9/mrjar/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Multi-Release: true 2 | 3 | -------------------------------------------------------------------------------- /archive/java-9/mrjar/README.md: -------------------------------------------------------------------------------- 1 | 2 | Multi-release jars, see http://openjdk.java.net/jeps/238 3 | 4 | Jar file has this structure: 5 | 6 | jar root 7 | - A.class 8 | - B.class 9 | - C.class 10 | - D.class 11 | - META-INF 12 | - versions 13 | - 9 14 | - A.class 15 | - B.class 16 | - 10 17 | - A.class 18 | 19 | Jar file structure is in the specification... 20 | There is still uncertainty about how source code will be structured: 21 | multi module project (maven/etc module not JPMS), or multiple versions of Java in one project? 22 | http://in.relation.to/2017/02/13/building-multi-release-jars-with-maven/ 23 | https://stackoverflow.com/questions/47648533/how-to-make-multi-release-jar-files-with-gradle 24 | 25 | Multi module projects are easier for existing tools 26 | For example, IntelliJ recommends separate IDEA modules since each project targets only one Java version 27 | https://blog.jetbrains.com/idea/2017/10/creating-multi-release-jar-files-in-intellij-idea/ 28 | 29 | I personally like the idea of keeping source for different versions in one project: 30 | - code that changes together should stay together 31 | - makes more sense to have one project build to one jar instead of multiple projects targeting a single jar 32 | - reduce risk of defining release version in subprojects to not be what the mrjar needs 33 | 34 | 35 | 36 | COMMANDS 37 | 38 | // this is a java 9 jar command way to do it 39 | rm -rf *.jar build/* build9/* 40 | javac -d build --release 8 src/main/java/*.java 41 | javac -d build9 --release 9 src/main/java-9/*.java 42 | jar --create --main-class=Application --file mrjar.jar -C build . --release 9 -C build9 . 43 | 44 | // see files 45 | jar --list --file mrjar.jar 46 | 47 | // execute jar file 48 | java -jar mrjar.jar 49 | ~/opt/jdk1.8.0_141/bin/java -jar mrjar.jar 50 | 51 | // see all relevant files at once 52 | gedit MANIFEST.MF src/main/java/Application.java src/main/java/Generator.java src/main/java/Generator.java src/main/java-9/Generator.java README.md & 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /archive/java-9/mrjar/src/main/java-9/Generator.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Set; 3 | 4 | public class Generator { 5 | 6 | public Set createStrings() { 7 | return Set.of("Java", "9"); 8 | } 9 | 10 | } 11 | 12 | -------------------------------------------------------------------------------- /archive/java-9/mrjar/src/main/java/Application.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.IOException; 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | import java.util.Set; 6 | 7 | public class Application { 8 | 9 | public static void main(String[] args) throws IOException { 10 | Generator gen = new Generator(); 11 | System.out.println("Generated strings: " + gen.createStrings()); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /archive/java-9/mrjar/src/main/java/Generator.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Set; 3 | import java.util.HashSet; 4 | 5 | public class Generator { 6 | 7 | public Set createStrings() { 8 | Set strings = new HashSet(); 9 | strings.add("Java"); 10 | strings.add("8"); 11 | return java.util.Collections.unmodifiableSet(strings); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /archive/java-9/process/Main.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.BufferedReader; 3 | import java.io.InputStreamReader; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) throws Exception { 8 | 9 | System.out.println("This process PID is " + ProcessHandle.current().pid()); 10 | System.out.println("(We can only get the PID this way in Java 9)"); 11 | 12 | ProcessBuilder builder = new ProcessBuilder("false"); 13 | builder.redirectErrorStream(true); 14 | 15 | Process childProcess = builder.start(); 16 | 17 | // define a function to call when the child process ends 18 | // and block until that function completes 19 | childProcess.onExit() 20 | .whenComplete( Main::mainFinished ) 21 | .get(); 22 | 23 | try (BufferedReader in = new BufferedReader(new InputStreamReader(childProcess.getInputStream()))) { 24 | in.lines().forEach(System.out::println); 25 | } 26 | 27 | } 28 | 29 | 30 | // TODO what do we do with the throwable? Can we trigger it? 31 | 32 | public static void mainFinished(Process p, Throwable t) { 33 | System.out.println("Throwable: " + t); 34 | System.out.println("Child process " + p.pid() + " finished."); 35 | System.out.println("(Can only post-process like this in Java 9, too)"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /archive/java-9/repl/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Experiments with Java 9's REPL 3 | 4 | 5 | ## To run jshell with your own project classes and dependencies 6 | 7 | https://github.com/johnpoth/jshell-maven-plugin 8 | 9 | https://github.com/bitterfox/jshell-gradle-plugin 10 | 11 | ## To try out a library like Google Guava: 12 | 13 | ``` 14 | wget http://central.maven.org/maven2/com/google/guava/guava/23.5-jre/guava-23.5-jre.jar 15 | jshell --class-path guava-23.5-jre.jar guava-test.sh 16 | ``` 17 | then inside jshell, run 18 | 19 | ``` 20 | /edit 21 | ``` 22 | 23 | ## To run Java code like a script 24 | 25 | ``` 26 | jshell hello.jsh 27 | ``` 28 | 29 | ## To load definitions at startup 30 | 31 | We can load some definitions so they are are always present (even after /reset). Note this completely replaces the default startup definitions. 32 | 33 | ``` 34 | jshell --startup bash.jsh 35 | ``` 36 | 37 | then inside jshell, run 38 | 39 | ``` 40 | ls() 41 | ``` 42 | 43 | ## Can run Java code to interactively work with remote systems 44 | 45 | One good example is interacting with a web API that uses Protobuf 46 | We can build objects and make network calls from the command line 47 | 48 | ## To run JShell from within your IDE: 49 | 50 | Add your own project as a library so IntelliJ can access it from JShell 51 | 52 | 53 | ## To specify JVM args 54 | 55 | launch with -J[args] 56 | 57 | For example, launch with jshell -J-Xmx2g 58 | 59 | note that now you can do something like this: 60 | jshell> new int[1000000000]; 61 | 62 | (maybe for a fast-running script, you can specify the Epsilon GC from Java 11) 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /archive/java-9/repl/bash.jsh: -------------------------------------------------------------------------------- 1 | // a startup file completely replaces the default imports 2 | // so need to bring in the imports yourself 3 | 4 | import java.util.* 5 | import java.io.* 6 | import java.nio.file.* 7 | import java.math.* 8 | import java.net.* 9 | import java.util.concurrent.* 10 | import java.util.prefs.* 11 | import java.util.regex.* 12 | 13 | 14 | void ls() throws IOException { 15 | Files.list(Paths.get(".")).forEach(System.out::println); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /archive/java-9/repl/guava-test.jsh: -------------------------------------------------------------------------------- 1 | 2 | // https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html 3 | import com.google.common.collect.*; 4 | ListMultimap multiMap = ArrayListMultimap.create(); 5 | multiMap.put("a", "1") 6 | multiMap.put("a", "2") 7 | multiMap.put("a", "1") 8 | multiMap.get("a") 9 | multiMap.remove("a", "1") 10 | multiMap.get("a") 11 | -------------------------------------------------------------------------------- /archive/java-9/repl/hello.jsh: -------------------------------------------------------------------------------- 1 | 2 | String javaString = "Look at me! I'm a scripting language!" 3 | 4 | System.out.println(javaString) 5 | 6 | System.out.println("Go home Java, you're drunk.") 7 | 8 | /exit 9 | -------------------------------------------------------------------------------- /archive/java14/DemoPatternMatching.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.java14; 2 | 3 | import org.w3c.dom.*; 4 | import javax.xml.parsers.*; 5 | import java.io.*; 6 | import java.nio.file.Files; 7 | import java.util.stream.Collectors; 8 | import java.nio.charset.StandardCharsets; 9 | 10 | 11 | public class DemoPatternMatching { 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | File xmlFile = new File("/Users/jason-dev/dev/java/java-14/books.xml"); 16 | String content = Files.lines(xmlFile.toPath()).collect(Collectors.joining()); 17 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 18 | DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 19 | InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); 20 | Document doc = dBuilder.parse(stream); 21 | 22 | Element root = doc.getDocumentElement(); 23 | System.out.println(root.getTagName()); 24 | 25 | // try for XML parser where you DO use instanceof... 26 | recursivePrint(root); 27 | 28 | // // Also useful for equals() implementations... 29 | 30 | 31 | // can do specific checks on typed object too 32 | // Object object = "this is a string"; 33 | // if (object instanceof String s) { 34 | // System.out.println(s + " ... has length " + s.length()); 35 | // } 36 | // else { 37 | // System.out.println("object is not a string"); 38 | // } 39 | // 40 | // Object t2 = ""; 41 | // if (t2 instanceof String s && ! s.isEmpty()) { 42 | // System.out.println(s + " ... has length " + s.length()); 43 | // } 44 | // else { 45 | // System.out.println("object is not a non-empty string"); 46 | // } 47 | } 48 | 49 | // https://docs.oracle.com/en/java/javase/11/docs/api/java.xml/org/w3c/dom/Node.html 50 | public static void recursivePrint(Node node) { 51 | 52 | if(node instanceof Attr) { 53 | // attr has getName() and getValue() 54 | Attr attribute = (Attr)node; 55 | System.out.println("Attr: " + attribute.getName() + ": " + attribute.getValue()); 56 | } 57 | if(node instanceof Element) { 58 | Element element = ((Element)node); 59 | System.out.println("Element: " + element.getTagName()); 60 | for(int a = 0; a < element.getAttributes().getLength(); a++) { 61 | recursivePrint(element.getAttributes().item(a)); 62 | } 63 | } 64 | if(node instanceof Text) { 65 | String text = ((Text)node).getWholeText(); 66 | System.out.println("Text: " + text); 67 | } 68 | if(node instanceof Comment) { 69 | String comment = ((Comment)node).getTextContent(); 70 | System.out.println("Comment: " + comment); 71 | } 72 | 73 | NodeList childNodes = node.getChildNodes(); 74 | for(int i = 0; i < childNodes.getLength(); i++) { 75 | Node child = childNodes.item(i); 76 | recursivePrint(child); 77 | } 78 | 79 | } 80 | 81 | public static void recursivePatternMatchingPrint(Node node) { 82 | 83 | if(node instanceof Attr attribute) { 84 | System.out.println("Attr: " + attribute.getName() + ": " + attribute.getValue()); 85 | } 86 | if(node instanceof Element element) { 87 | System.out.println("Element: " + element.getTagName()); 88 | for(int a = 0; a < element.getAttributes().getLength(); a++) { 89 | recursivePrint(element.getAttributes().item(a)); 90 | } 91 | } 92 | if(node instanceof Text text) { 93 | System.out.println("Text: " + text.getWholeText()); 94 | } 95 | if(node instanceof Comment comment) { 96 | System.out.println("Comment: " + comment.getTextContent()); 97 | } 98 | 99 | NodeList childNodes = node.getChildNodes(); 100 | for(int i = 0; i < childNodes.getLength(); i++) { 101 | Node child = childNodes.item(i); 102 | recursivePrint(child); 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /archive/java14/DemoSwitch.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.java14; 2 | 3 | import java.util.*; 4 | import java.util.function.*; 5 | import java.util.stream.*; 6 | import static java.util.Optional.*; 7 | import static java.util.stream.Collectors.*; 8 | 9 | import org.w3c.dom.*; 10 | import javax.xml.parsers.*; 11 | import java.io.*; 12 | import java.nio.file.Files; 13 | import java.util.stream.Collectors; 14 | import java.nio.charset.StandardCharsets; 15 | import static org.w3c.dom.Node.*; 16 | 17 | public class DemoSwitch { 18 | 19 | public static void main(String[] args) throws Exception { 20 | 21 | DAY_OF_WEEK day = DAY_OF_WEEK.MONDAY; 22 | 23 | switch (day) { 24 | case MONDAY, FRIDAY, SUNDAY -> System.out.println(6); 25 | case TUESDAY -> System.out.println(7); 26 | case THURSDAY, SATURDAY -> System.out.println(8); 27 | case WEDNESDAY -> System.out.println(9); 28 | } 29 | 30 | // switch expression 31 | int numLetters = switch (day) { 32 | case MONDAY, FRIDAY, SUNDAY -> 6; 33 | case TUESDAY -> 7; 34 | case THURSDAY, SATURDAY -> 8; 35 | case WEDNESDAY -> 9; 36 | }; 37 | 38 | System.out.println(numLetters); 39 | 40 | 41 | // TODO yield statement, difference from return? 42 | // see switch expression vs statement: statement can NOT use yield, expression CAN. 43 | // flipped for break 44 | // yield becomes the value of the evaulated expression, don't use return because you'd return from the function 45 | // use yield if you need to evaluate a block of code in the switch case. 46 | 47 | // TODO use short values from Node.getNodeType() and switch on short to demonstrate parsing 48 | // File xmlFile = new File("/Users/jason-dev/dev/java/java-14/books.xml"); 49 | // String content = Files.lines(xmlFile.toPath()).collect(Collectors.joining()); 50 | String content = booksXML; 51 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 52 | DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 53 | InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); 54 | Document doc = dBuilder.parse(stream); 55 | 56 | Element root = doc.getDocumentElement(); 57 | 58 | // TODO demonstrate what happens on missing case 59 | // (switch on short needs a default) 60 | 61 | recursiveSwitchPrint(root, ""); 62 | } 63 | 64 | enum DAY_OF_WEEK { 65 | MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY 66 | } 67 | 68 | // based on http://www.java2s.com/Code/JavaAPI/org.w3c.dom/NodegetNodeType.htm 69 | public static void recursiveSwitchPrint(Node node, String indent) { 70 | 71 | short nodeType = node.getNodeType(); 72 | 73 | String type = switch(nodeType) { 74 | case ELEMENT_NODE -> "Element"; 75 | case DOCUMENT_TYPE_NODE -> "Document type"; 76 | case ENTITY_NODE -> "Entity"; 77 | case ENTITY_REFERENCE_NODE -> "Entity reference"; 78 | case NOTATION_NODE -> "Notation"; 79 | case TEXT_NODE -> "Text"; 80 | case COMMENT_NODE -> "Comment"; 81 | case CDATA_SECTION_NODE -> "CDATA Section"; 82 | case ATTRIBUTE_NODE -> "Attribute"; 83 | case PROCESSING_INSTRUCTION_NODE -> "Attribute"; 84 | default -> throw new IllegalArgumentException("Node type not recognized: " + nodeType); 85 | }; 86 | 87 | System.out.println(indent + type); 88 | 89 | NodeList childNodes = node.getChildNodes(); 90 | for(int i = 0; i < childNodes.getLength(); i++) { 91 | Node child = childNodes.item(i); 92 | recursiveSwitchPrint(child, indent + " "); 93 | } 94 | } 95 | 96 | 97 | // Can use text blocks for test content 98 | private final static String booksXML = """ 99 | 100 | 101 | 102 | 103 | Gambardella, Matthew 104 | XML Developer's Guide 105 | Computer 106 | 44.95 107 | 2000-10-01 108 | An in-depth look at creating applications 109 | with XML. 110 | 111 | 112 | Ralls, Kim 113 | Midnight Rain 114 | Fantasy 115 | 5.95 116 | 2000-12-16 117 | A former architect battles corporate zombies, 118 | an evil sorceress, and her own childhood to become queen 119 | of the world. 120 | 121 | 122 | Corets, Eva 123 | Maeve Ascendant 124 | Fantasy 125 | 5.95 126 | 2000-11-17 127 | After the collapse of a nanotechnology 128 | society in England, the young survivors lay the 129 | foundation for a new society. 130 | 131 | 132 | Corets, Eva 133 | Oberon's Legacy 134 | Fantasy 135 | 5.95 136 | 2001-03-10 137 | In post-apocalypse England, the mysterious 138 | agent known only as Oberon helps to create a new life 139 | for the inhabitants of London. Sequel to Maeve 140 | Ascendant. 141 | 142 | 143 | Corets, Eva 144 | The Sundered Grail 145 | Fantasy 146 | 5.95 147 | 2001-09-10 148 | The two daughters of Maeve, half-sisters, 149 | battle one another for control of England. Sequel to 150 | Oberon's Legacy. 151 | 152 | 153 | Randall, Cynthia 154 | Lover Birds 155 | Romance 156 | 4.95 157 | 2000-09-02 158 | When Carla meets Paul at an ornithology 159 | conference, tempers fly as feathers get ruffled. 160 | 161 | 162 | Thurman, Paula 163 | Splish Splash 164 | Romance 165 | 4.95 166 | 2000-11-02 167 | A deep sea diver finds true love twenty 168 | thousand leagues beneath the sea. 169 | 170 | 171 | Knorr, Stefan 172 | Creepy Crawlies 173 | Horror 174 | 4.95 175 | 2000-12-06 176 | An anthology of horror stories about roaches, 177 | centipedes, scorpions and other insects. 178 | 179 | 180 | Kress, Peter 181 | Paradox Lost 182 | Science Fiction 183 | 6.95 184 | 2000-11-02 185 | After an inadvertant trip through a Heisenberg 186 | Uncertainty Device, James Salway discovers the problems 187 | of being quantum. 188 | 189 | 190 | """; 191 | } -------------------------------------------------------------------------------- /archive/java14/DemoTextBlocks.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.java14; 2 | 3 | import java.util.*; 4 | import java.util.function.*; 5 | import java.util.stream.*; 6 | import static java.util.Optional.*; 7 | import static java.util.stream.Collectors.*; 8 | import javax.script.ScriptEngine; 9 | import javax.script.ScriptEngineManager; 10 | 11 | 12 | public class DemoTextBlocks { 13 | 14 | public static void main(String[] args) throws Exception { 15 | 16 | 17 | ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); 18 | engine.eval(""" 19 | function hello() { 20 | print('"Hello, world"'); 21 | } 22 | 23 | hello(); 24 | """); 25 | 26 | String query = """ 27 | SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` 28 | WHERE `CITY` = 'INDIANAPOLIS' 29 | ORDER BY `EMP_ID`, `LAST_NAME`; 30 | """; 31 | } 32 | } -------------------------------------------------------------------------------- /archive/java14/FlightRecorderDemo.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.java14; 2 | 3 | import java.util.*; 4 | import java.util.function.*; 5 | import java.util.stream.*; 6 | import static java.util.Optional.*; 7 | import static java.util.stream.Collectors.*; 8 | 9 | public class FlightRecorderDemo { 10 | 11 | public static void main(String[] args) { 12 | 13 | 14 | // java --enable-preview --source 14 FlightRecorderDemo.java 15 | 16 | 17 | // https://stackoverflow.com/questions/57841060/why-have-i-more-than-one-jfr-recording 18 | 19 | // Try JFR streaming 20 | // https://qconsf.com/system/files/presentation-slides/mikael_vidstedt_-_qconsf-continuous_monitoring_with_jdk_flight_recorder.pdf 21 | 22 | // https://mbien.dev/blog/entry/jfr-event-streaming-with-java 23 | 24 | // https://download.java.net/java/early_access/jdk14/docs/api/jdk.jfr/jdk/jfr/package-summary.html 25 | 26 | // https://github.com/jiekang/jfr-datasource 27 | 28 | 29 | //# Start a recording 30 | // java -XX:StartFlightRecording ... 31 | //# Start a recording, and store it to file 32 | // java –XX:StartFlightRecording:filename=/tmp/foo.jfr ... 33 | //# Enable recording in an already running VM (pid 4711) 34 | //# jcmd JFR.start [options] 35 | // jcmd 4711 JFR.start OR jcmd MyApplication JFR.start 36 | //# Dump a recording from running VM (pid 4711), at most 50MB of data 37 | // jcmd 4711 JFR.dump maxsize=50MB 38 | 39 | // # Print summary of recording 40 | // jfr summary myrecording.jfr 41 | //# Print events 42 | // jfr print myrecording.jfr 43 | //# Print events in JSON format 44 | // jfr print --json myrecording.jfr 45 | //# Print GC related events 46 | // jfr print --categories "GC" myrecording.jfr 47 | 48 | // https://download.java.net/java/early_access/jdk14/docs/api/jdk.jfr/jdk/jfr/consumer/RecordingStream.html 49 | 50 | // A list of available event names can be retrieved 51 | // jshell> jdk.jfr.FlightRecorder.getFlightRecorder().getEventTypes().stream().map(t -> t.getName()).forEach(n -> System.out.println(n)); 52 | 53 | 54 | 55 | startEventStream(List.of("jdk.CPULoad"), java.time.Duration.ofSeconds(15)); 56 | 57 | try{Thread.sleep(3_000);} 58 | catch(InterruptedException ie) {} 59 | 60 | // try pegging the CPU and telling by the event stream when the computation is happening 61 | // TODO log if the event if over a threshold 62 | IntStream.range(0, 20).parallel().forEach( s -> { 63 | java.security.SecureRandom random = new java.security.SecureRandom(java.math.BigInteger.ONE.toByteArray()); 64 | for(long i=0; i < 1_000_000; i++) { 65 | // do a CPU intensive operation 66 | int j = random.nextInt(); 67 | // allocate some memory 68 | var x = new Object() { int k = j; }; 69 | } 70 | }); 71 | 72 | try{Thread.sleep(3_000);} 73 | catch(InterruptedException ie) {} 74 | } 75 | 76 | public static void startEventStream(List eventNames, java.time.Duration eventStreamDuration) { 77 | 78 | java.time.Duration pollInterval = java.time.Duration.ofMillis(500); 79 | 80 | // TODO can we call .close() on the RecordingStream? What if we wanted to close it manually? 81 | 82 | // TODO are we having trouble calling .start() in other ways because we didn't create the FlightRecorder? 83 | // or does creating a RecordingStream create the FlightRecorder for you? 84 | new Thread(() -> { 85 | try (jdk.jfr.consumer.RecordingStream rs = new jdk.jfr.consumer.RecordingStream()) { 86 | 87 | // period is when the event is emitted, 88 | // not when output is flushed to consumer (seems to only be printed once per second regardless of event period) 89 | eventNames.forEach(name -> { 90 | rs.enable(name).withPeriod(pollInterval); 91 | rs.onEvent(name, event -> System.out.println(event)); 92 | }); 93 | 94 | // TODO try configuration with .setFlushInterval() 95 | // make notes contrasting with event period. 96 | // can we make it write out more frequently? 97 | // rs.setFlushInterval(pollInterval); 98 | 99 | rs.setEndTime(java.time.Instant.now().plus(eventStreamDuration)); 100 | 101 | // this blocks on the current Thread 102 | rs.start(); 103 | } 104 | }).start(); 105 | 106 | } 107 | 108 | 109 | 110 | // from javadocs 111 | 112 | // jdk.jfr.Configuration 113 | //Configuration c = Configuration.getConfiguration("default"); 114 | //try (var rs = new RecordingStream(c)) { 115 | // rs.onEvent("jdk.GarbageCollection", System.out::println); 116 | // rs.onEvent("jdk.CPULoad", System.out::println); 117 | // rs.onEvent("jdk.JVMInformation", System.out::println); 118 | // rs.start(); 119 | // } 120 | //} 121 | // rs.enable("jdk.CPULoad").withPeriod(java.time.Duration.ofSeconds(1)); 122 | // rs.onEvent("jdk.CPULoad", event -> System.out.println(event)); // .getFloat("machineTotal"))); 123 | 124 | // jdk.PhysicalMemory 125 | // jdk.JVMInformation 126 | //jdk.OSInformation 127 | // jdk.SocketWrite 128 | //jdk.SocketRead 129 | //jdk.FileWrite 130 | //jdk.FileRead 131 | // jdk.SystemProcess 132 | //jdk.CPUInformation 133 | //jdk.CPUTimeStampCounter 134 | //jdk.CPULoad 135 | //jdk.ThreadCPULoad 136 | //jdk.ThreadContextSwitchRate 137 | //jdk.NetworkUtilization 138 | //jdk.JavaThreadStatistics 139 | // jdk.ObjectCount 140 | 141 | 142 | 143 | 144 | } -------------------------------------------------------------------------------- /archive/java14/books.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Gambardella, Matthew 6 | XML Developer's Guide 7 | Computer 8 | 44.95 9 | 2000-10-01 10 | An in-depth look at creating applications 11 | with XML. 12 | 13 | 14 | Ralls, Kim 15 | Midnight Rain 16 | Fantasy 17 | 5.95 18 | 2000-12-16 19 | A former architect battles corporate zombies, 20 | an evil sorceress, and her own childhood to become queen 21 | of the world. 22 | 23 | 24 | Corets, Eva 25 | Maeve Ascendant 26 | Fantasy 27 | 5.95 28 | 2000-11-17 29 | After the collapse of a nanotechnology 30 | society in England, the young survivors lay the 31 | foundation for a new society. 32 | 33 | 34 | Corets, Eva 35 | Oberon's Legacy 36 | Fantasy 37 | 5.95 38 | 2001-03-10 39 | In post-apocalypse England, the mysterious 40 | agent known only as Oberon helps to create a new life 41 | for the inhabitants of London. Sequel to Maeve 42 | Ascendant. 43 | 44 | 45 | Corets, Eva 46 | The Sundered Grail 47 | Fantasy 48 | 5.95 49 | 2001-09-10 50 | The two daughters of Maeve, half-sisters, 51 | battle one another for control of England. Sequel to 52 | Oberon's Legacy. 53 | 54 | 55 | Randall, Cynthia 56 | Lover Birds 57 | Romance 58 | 4.95 59 | 2000-09-02 60 | When Carla meets Paul at an ornithology 61 | conference, tempers fly as feathers get ruffled. 62 | 63 | 64 | Thurman, Paula 65 | Splish Splash 66 | Romance 67 | 4.95 68 | 2000-11-02 69 | A deep sea diver finds true love twenty 70 | thousand leagues beneath the sea. 71 | 72 | 73 | Knorr, Stefan 74 | Creepy Crawlies 75 | Horror 76 | 4.95 77 | 2000-12-06 78 | An anthology of horror stories about roaches, 79 | centipedes, scorpions and other insects. 80 | 81 | 82 | Kress, Peter 83 | Paradox Lost 84 | Science Fiction 85 | 6.95 86 | 2000-11-02 87 | After an inadvertant trip through a Heisenberg 88 | Uncertainty Device, James Salway discovers the problems 89 | of being quantum. 90 | 91 | 92 | O'Brien, Tim 93 | Microsoft .NET: The Programming Bible 94 | Computer 95 | 36.95 96 | 2000-12-09 97 | Microsoft's .NET initiative is explored in 98 | detail in this deep programmer's reference. 99 | 100 | 101 | O'Brien, Tim 102 | MSXML3: A Comprehensive Guide 103 | Computer 104 | 36.95 105 | 2000-12-01 106 | The Microsoft MSXML3 parser is covered in 107 | detail, with attention to XML DOM interfaces, XSLT processing, 108 | SAX and more. 109 | 110 | 111 | Galos, Mike 112 | Visual Studio 7: A Comprehensive Guide 113 | Computer 114 | 49.95 115 | 2001-04-16 116 | Microsoft Visual Studio 7 is explored in depth, 117 | looking at how Visual Basic, Visual C++, C#, and ASP+ are 118 | integrated into a comprehensive development 119 | environment. 120 | 121 | -------------------------------------------------------------------------------- /archive/lvti/Main.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | package org.thinkbigthings.demo.lvti; 5 | 6 | import java.lang.annotation.*; 7 | import java.util.*; 8 | import java.util.function.*; 9 | import java.time.*; 10 | import static java.util.stream.Collectors.*; 11 | 12 | 13 | /** 14 | 15 | http://openjdk.java.net/jeps/286 16 | 17 | http://benjiweber.co.uk/blog/2018/03/03/representing-the-impractical-and-impossible-with-jdk-10-var/amp/ 18 | 19 | https://gist.github.com/benjiman/a8945f378691f4c1d258a12bed825ec2 20 | 21 | */ 22 | public class Main { 23 | 24 | public static void main(String[] args) { 25 | 26 | // can simplify simple declarations, but that's just convenience, doesn't change much 27 | var names = List.of("here", "is", "a", "word", "list"); 28 | System.out.println(names); 29 | 30 | // "Poly Expressions" that require such a type, 31 | // like lambdas, method references, and array initializers, trigger an error 32 | // 33 | // https://stackoverflow.com/questions/49134118/array-initializer-needs-an-explicit-target-type-why 34 | // 35 | // var out = System.out::println; // ILLEGAL! 36 | // var f = (int x) -> x*x; // ILLEGAL! 37 | // 38 | // var f1 = (UnaryOperator)((Integer x) -> x * x); // LEGAL (but should we do this?) 39 | // UnaryOperator f2 = x -> x * x; // LEGAL (and probably more readable) 40 | 41 | // but this is legal 42 | var f = (IntUnaryOperator) (int a) -> a * a; 43 | System.out.println(f.applyAsInt(2)); 44 | 45 | // and this may be more readable 46 | IntUnaryOperator f2 = a -> a * a; 47 | 48 | 49 | // you can put @NotNull on a lambda parameter 50 | // annotations can be applied to local variables and lambda variables 51 | var isEven = (Predicate) x -> x%2==0; // legal with Java 10 52 | Predicate isEven2 = (@NotNull var x) -> x%2==0; // legal with Java 11 (var on lambda parameter) 53 | 54 | // there is no val/let, can use "final var" 55 | final var string = "can't touch this"; 56 | // string = ""; // Causes error at compile time 57 | 58 | // can declare anonymous classes and use a new scoped type 59 | // note this is not dynamic typing! Everything still has a fixed type known at compile time 60 | var person = new Object() { 61 | String name = "bob"; 62 | int age = 5; 63 | }; 64 | 65 | // even if declared as Object (without var), this is impossible before Java 10 66 | System.out.println(person.name + " aged " + person.age); 67 | 68 | 69 | // what if you want to process a stream of data and retain the original with its processed version? 70 | // here's a Java 8 approach. This works but only with two values 71 | // what if you wanted to maintain a stream of three processed values? Nothing built-in anymore! 72 | // not to mention, using the built-in Map Entry type is not so readable. 73 | names.stream() 74 | .map(n -> new AbstractMap.SimpleEntry<>(n, n.length())) 75 | .filter(t -> t.getValue() > 3) 76 | .map(t -> t.getKey()) 77 | .forEach(System.out::println); 78 | 79 | 80 | // easier to make tuple types, 81 | // can pass multiple values through the Stream API in a type safe way 82 | // this is impossible before Java 10 83 | // https://stackoverflow.com/questions/43987285/implied-anonymous-types-inside-lambdas 84 | // https://blog.codefx.org/java/tricks-var-anonymous-classes/ 85 | // cons: could affect readability, memory, and risk linking to enclosing class 86 | names.stream() 87 | .map(n -> new Object() { 88 | String word = n; 89 | int length = n.length(); 90 | Instant processedTimestamp = Instant.now(); 91 | }) 92 | .filter(t -> t.length > 3) 93 | .map(t -> t.word) 94 | .forEach(System.out::println); 95 | 96 | // an anonymous inner class hold a reference to the enclosing class, 97 | // what is the enclosing class in this case: the stream ? 98 | // I think this is a poor practice like double brace initialization 99 | // this is called out as a "neat trick" but not by the JEP or language designers themselves, 100 | // which likely indicates that this is not an intended use case 101 | 102 | // we can collect the anonymous type to a Set 103 | // the destination set needs to be "var" instead of "Set" 104 | // otherwise it will think you mean Set and you'll lose access to the type 105 | // Note that this is LOCAL type inference... 106 | // the type of an anonymous subclass can't be in the return signature of a method 107 | System.out.println("collecting"); 108 | var longNames = names.stream() 109 | .map(n -> new Object() { 110 | String word = n; 111 | int length = n.length(); 112 | Instant processedTimestamp = Instant.now(); 113 | }) 114 | .filter(t -> t.length > 3) 115 | .collect(toSet()); 116 | System.out.println(longNames.iterator().next().processedTimestamp); 117 | 118 | } 119 | 120 | @Retention(RetentionPolicy.RUNTIME) 121 | @Target(ElementType.PARAMETER) 122 | public @interface NotNull { 123 | public boolean enabled() default true; 124 | } 125 | 126 | 127 | } 128 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.thinkbigthings' 6 | version '1.0-SNAPSHOT' 7 | 8 | java { 9 | sourceCompatibility = JavaVersion.VERSION_23 10 | toolchain { 11 | languageVersion = JavaLanguageVersion.of(23) 12 | } 13 | } 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | 21 | implementation 'org.springframework.boot:spring-boot-starter-test:3.4.1' 22 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa:3.4.1' 23 | implementation 'org.springframework.boot:spring-boot-starter-validation:3.4.1' 24 | 25 | implementation 'com.fasterxml.jackson.core:jackson-core:2.17.2' 26 | implementation 'com.fasterxml.jackson.core:jackson-annotations:2.17.2' 27 | implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0' 28 | 29 | implementation 'com.google.code.gson:gson:2.8.6' 30 | 31 | testImplementation 'org.junit.jupiter:junit-jupiter:5.10.3' 32 | testImplementation 'org.mockito:mockito-junit-jupiter:5.12.0' 33 | } 34 | 35 | test { 36 | useJUnitPlatform() 37 | } 38 | 39 | // use preview features 40 | tasks.withType(JavaCompile) { 41 | options.compilerArgs += "--enable-preview" 42 | // options.compilerArgs += "-Xlint:preview" 43 | options.compilerArgs += "-Xlint:unchecked" 44 | options.compilerArgs += "-Xlint:deprecation" 45 | } 46 | tasks.withType(Test) { 47 | jvmArgs += "--enable-preview" 48 | } 49 | tasks.withType(JavaExec) { 50 | jvmArgs += '--enable-preview' 51 | } 52 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thinkbigthings/java/a34fa9efc765290e4498414392c00b3265b73ec7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-demo' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/httpclient/Main.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.httpclient; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | import java.net.http.*; 6 | import java.util.*; 7 | import java.util.concurrent.*; 8 | 9 | import static java.net.http.HttpRequest.*; 10 | import static java.net.http.HttpResponse.*; 11 | import static java.nio.charset.StandardCharsets.*; 12 | 13 | public class Main { 14 | 15 | public static void main(String[] args) throws Exception { 16 | 17 | // TODO stream request and response, all async 18 | // does the streaming method wait for the stream to finish before returning? 19 | // https://download.java.net/java/early_access/jdk11/docs/api/java.net.http/java/net/http/HttpRequest.BodyPublishers.html 20 | 21 | 22 | String stackOverflow = "https://stackoverflow.com"; 23 | requestStreaming(stackOverflow); 24 | // requestSync(stackOverflow); 25 | 26 | System.out.println("Program done."); 27 | System.exit(0); 28 | } 29 | 30 | public static void requestSync(String url) throws Exception { 31 | 32 | // clients are immutable and thread safe 33 | final HttpClient client = HttpClient.newHttpClient(); 34 | 35 | // GET 36 | HttpResponse response = client.send( 37 | HttpRequest 38 | .newBuilder(new URI(url)) 39 | .GET() 40 | .build(), 41 | BodyHandlers.ofString() 42 | ); 43 | 44 | int statusCode = response.statusCode(); 45 | processResponseBody(response.body()); 46 | } 47 | 48 | public static void requestStreaming(String url) throws Exception { 49 | 50 | final HttpClient client = HttpClient.newHttpClient(); 51 | 52 | CompletableFuture> response = client.sendAsync( 53 | HttpRequest 54 | .newBuilder(new URI(url)) 55 | .GET() 56 | .build(), 57 | BodyHandlers.ofString() 58 | ); 59 | 60 | response.thenAccept( s -> processResponseBody(s.body())).join(); 61 | } 62 | 63 | public static void processResponseBody(String body) { 64 | processResponseBody(new ByteArrayInputStream(body.getBytes(UTF_8))); 65 | } 66 | 67 | public static void processResponseBody(InputStream stream) { 68 | 69 | try(BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) { 70 | br.lines().forEach(Main::processLine); 71 | } 72 | catch(Exception e) { 73 | e.printStackTrace(); 74 | } 75 | System.out.println("Processing Done!"); 76 | } 77 | 78 | public static void processLine(String line) { 79 | System.out.print("."); 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/BuildablePerson.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | // This is one possible Builder 4 | // Good news it's an easy one-liner per method, no separate Builder class, immutable by default, no .build() at the end 5 | // Bad news is it's a lot of boilerplate so could be error prone, and creates new object per builder method call 6 | public record BuildablePerson(String firstName, String lastName) { 7 | 8 | public BuildablePerson() { 9 | this("", ""); 10 | } 11 | 12 | public static BuildablePerson newPerson() { 13 | return new BuildablePerson(); 14 | } 15 | 16 | public BuildablePerson withFirstName(String newFirstName) { 17 | return new BuildablePerson(newFirstName, lastName); 18 | } 19 | 20 | public BuildablePerson withLastName(String newLastName) { 21 | return new BuildablePerson(firstName, newLastName); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/CheckedFunction.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import java.util.function.Function; 4 | 5 | @FunctionalInterface 6 | public interface CheckedFunction { 7 | 8 | R apply(T t) throws Exception; 9 | 10 | default Function uncheck(CheckedFunction checkedFunction) { 11 | return t -> { 12 | try { 13 | return checkedFunction.apply(t); 14 | } catch (Exception e) { 15 | throw new RuntimeException(e); 16 | } 17 | }; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/Expression.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | public sealed interface Expression permits Expression.IntExp, Expression.AddExp, Expression.SubtractExp { 4 | 5 | int value(); 6 | 7 | // "final" here is kind of unnecessary since records are already final 8 | // but it gets rid of the IDE warning :) 9 | final record IntExp(int value) implements Expression { 10 | } 11 | 12 | final record AddExp(Expression left, Expression right) implements Expression { 13 | public int value() { 14 | return left.value() + right.value(); 15 | } 16 | } 17 | 18 | final record SubtractExp(Expression left, Expression right) implements Expression { 19 | public int value() { 20 | return left.value() - right.value(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/Functional.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import java.util.function.Function; 4 | 5 | public class Functional { 6 | 7 | @FunctionalInterface 8 | public interface CheckedFunction { 9 | R apply(T t) throws Exception; 10 | } 11 | 12 | public static Function uncheck(CheckedFunction checkedFunction) { 13 | return t -> { 14 | try { 15 | return checkedFunction.apply(t); 16 | } catch (Exception e) { 17 | throw new RuntimeException(e); 18 | } 19 | }; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/Try.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import java.util.List; 4 | import java.util.Objects; 5 | import java.util.function.Function; 6 | import java.util.stream.Collector; 7 | import java.util.stream.Stream; 8 | 9 | import static java.util.stream.Collectors.flatMapping; 10 | import static java.util.stream.Collectors.toList; 11 | 12 | 13 | record Try(Exception exception, R result) { 14 | 15 | public Try { 16 | if((exception == null && result == null) || (exception != null && result != null)) { 17 | throw new IllegalArgumentException("Must have exactly one non-null argument"); 18 | } 19 | } 20 | 21 | public static Function> tryCatch(CheckedFunction function) { 22 | return t -> { 23 | try { 24 | // require not null result, otherwise it is hard to tell if this Try is a result or an exception 25 | R result = Objects.requireNonNull(function.apply(t)); 26 | return new Try<>(null, result); 27 | } catch (Exception ex) { 28 | return new Try<>(ex, null); 29 | } 30 | }; 31 | } 32 | 33 | public static Collector, ?, List> toExceptions() { 34 | return flatMapping((Try t) -> Stream.ofNullable(t.exception()), toList()); 35 | } 36 | 37 | public static Collector, ?, List> toResults() { 38 | return flatMapping((Try t) -> Stream.ofNullable(t.result()), toList()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/jpa/Store.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records.jpa; 2 | 3 | import jakarta.persistence.*; 4 | import jakarta.validation.constraints.NotNull; 5 | 6 | @Entity 7 | @Table(name = "store") 8 | public class Store { 9 | 10 | @Id 11 | @GeneratedValue(strategy= GenerationType.IDENTITY) 12 | @Column(name = "id", updatable = false, insertable = false, nullable = false) 13 | private Long id; 14 | 15 | @NotNull 16 | @Column(unique=true) 17 | private String name = ""; 18 | 19 | @NotNull 20 | private String website = ""; 21 | 22 | protected Store() {} 23 | 24 | public Store(String name, String website) { 25 | this.name = name; 26 | this.website = website; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public String getWebsite() { 38 | return website; 39 | } 40 | 41 | public void setWebsite(String website) { 42 | this.website = website; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/jpa/StoreRecord.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records.jpa; 2 | 3 | public record StoreRecord(String name, String website) { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/thinkbigthings/demo/records/jpa/StoreRepository.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records.jpa; 2 | 3 | 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.data.jpa.repository.Query; 8 | 9 | import java.util.Optional; 10 | 11 | public interface StoreRepository extends JpaRepository { 12 | 13 | Optional findByName(String name); 14 | 15 | @Query("SELECT new org.thinkbigthings.demo.records.jpa.StoreRecord(s.name, s.website) " + 16 | "FROM Store s ORDER BY s.name ASC ") 17 | Page loadSummaries(Pageable page); 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/gatherers/FunctionalFinders.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.gatherers; 2 | 3 | 4 | import java.util.Optional; 5 | import java.util.stream.Collector; 6 | import java.util.stream.Collectors; 7 | 8 | public class FunctionalFinders { 9 | 10 | 11 | /** 12 | * Use this when having more than one element in the stream would be an error. 13 | * 14 | * Optional<User> resultUser = users.stream() 15 | * .filter(user -> user.getId() == 100) 16 | * .collect(findOne()); 17 | * 18 | * @param Type 19 | * @return Collection 20 | */ 21 | public static Collector> toOne() { 22 | return Collectors.collectingAndThen( 23 | Collectors.toList(), 24 | list -> { 25 | if (list.size() > 1) { 26 | String m = "Must have zero or one element, found " + list.size(); 27 | throw new IllegalArgumentException(m); 28 | } 29 | return list.size() == 1 ? Optional.of(list.get(0)) : Optional.empty(); 30 | } 31 | ); 32 | } 33 | 34 | /** 35 | * Use this when not having exactly one element in the stream would be an error. 36 | * 37 | * Usage: 38 | * 39 | * User resultUser = users.stream() 40 | * .filter(user -> user.getId() == 100) 41 | * .collect(findExactlyOne()); 42 | * 43 | * @param Type 44 | * @return exactly one element. 45 | */ 46 | public static Collector toExactlyOne() { 47 | return Collectors.collectingAndThen( 48 | Collectors.toList(), 49 | list -> { 50 | if (list.size() != 1) { 51 | String m = "Must have exactly one element, found " + list.size(); 52 | throw new IllegalArgumentException(m); 53 | } 54 | return list.get(0); 55 | } 56 | ); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/gatherers/GathererTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.gatherers; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.*; 6 | import java.util.function.BiConsumer; 7 | import java.util.function.BinaryOperator; 8 | import java.util.function.Function; 9 | import java.util.function.Supplier; 10 | import java.util.stream.*; 11 | 12 | import static java.util.stream.Collectors.toList; 13 | import static java.util.stream.Gatherers.fold; 14 | import static java.util.stream.Gatherers.scan; 15 | import static java.util.stream.IntStream.iterate; 16 | import static org.thinkbigthings.demo.gatherers.FunctionalFinders.toExactlyOne; 17 | 18 | 19 | public class GathererTest { 20 | 21 | // static method that returns a Gatherer, this Gatherer implements a stream map 22 | public static Gatherer map(Function mapper) { 23 | return Gatherer.of( (unused, element, downstream) -> downstream.push(mapper.apply(element)) ); 24 | } 25 | 26 | @Test 27 | public void testGathererAsMapper() { 28 | 29 | // Stream::gather(Gatherer) is to intermediate operations what Stream::collect(Collector) is to terminal operations 30 | // Gatherers can transform elements in a one-to-one, one-to-many, many-to-one, or many-to-many fashion 31 | 32 | // here we can reimplement simple mapping with a gatherer that is one-to-one 33 | var words = List.of("here", "is", "a", "word", "list"); 34 | words.stream() 35 | .gather(map(String::toUpperCase)) 36 | .forEach(System.out::println); 37 | } 38 | 39 | // one of the upcoming gatherer libraries has a rolling average gatherer, I think 40 | private Optional average(List window) { 41 | return window.stream().flatMapToDouble(DoubleStream::of).average().stream().boxed().findFirst(); 42 | } 43 | 44 | @Test 45 | public void testGathererSlidingWindow() { 46 | 47 | // sliding window can be used for things like smoothing functions 48 | // there are better curve-fitting algorithms, but this illustrates the idea 49 | 50 | var xValues = IntStream.range(1, 62) 51 | .mapToDouble(i -> i / 10d) 52 | .boxed() 53 | .toList(); 54 | 55 | var yValues = xValues.stream() 56 | .map(Math::sin) 57 | .toList(); 58 | 59 | var noisyValues = yValues.stream() 60 | .map(i -> i + ((0.4 * Math.random()) - 0.2)) 61 | .toList(); 62 | 63 | var smoothedValues = noisyValues.stream() 64 | .gather(Gatherers.windowSliding(5)) 65 | .map(this::average) 66 | .flatMap(Optional::stream) 67 | .toList(); 68 | 69 | 70 | System.out.println("X Values"); 71 | xValues.forEach(System.out::println); 72 | 73 | System.out.println("Noisy Values"); 74 | noisyValues.forEach(System.out::println); 75 | 76 | System.out.println("Smoothed values"); 77 | smoothedValues.forEach(System.out::println); 78 | 79 | 80 | } 81 | 82 | @Test 83 | public void testFold() { 84 | 85 | // looking at the source code for fold() and scan() in Gatherers.java is helpful 86 | 87 | 88 | // reduce is a kind of fold. Reduction takes a stream and turns it into a single value. 89 | // Folding also does this, but it loosens the requirements: 90 | // 1) that the return type is of the same type as the stream elements 91 | // 2) that the combiner is associative 92 | // 3) the initializer on fold is a generator function not a static value. 93 | // System.out.println("Fold example: Fibonacci sequence"); 94 | // Stream.of(1, 2, 3, 4, 5) 95 | // .gather(Gatherers.fold(() -> 1, (a, b) -> a * b)) 96 | // .forEach(System.out::println); 97 | 98 | 99 | var freqMap = Arrays.stream("gatherer".split("")) 100 | .gather(fold(HashMap::new, (map, str) -> { 101 | // since we're using fold, we can mutate the map in place 102 | map.put(str, map.getOrDefault(str, 0) + 1); 103 | return map; 104 | })) 105 | .findFirst() // since we only get one element out of fold, we can just grab the first one 106 | .orElseGet(HashMap::new); 107 | 108 | System.out.println(freqMap); 109 | } 110 | 111 | @Test 112 | public void testHistogram() { 113 | 114 | class Histogram { 115 | 116 | private final int binSize; 117 | private final NavigableMap map; 118 | 119 | public Histogram(int binSize) { 120 | this.binSize = binSize; 121 | this.map = new TreeMap<>(); 122 | } 123 | 124 | public Histogram putValue(Integer value) { 125 | int bin = value - (value % binSize); 126 | map.put(bin, map.getOrDefault(bin, 0) + 1); 127 | return this; 128 | } 129 | 130 | public NavigableMap map() { 131 | // set unfilled bins 132 | int minBin = map.firstKey(); 133 | int maxBin = map.lastKey(); 134 | IntStream.iterate(minBin, b -> b <= maxBin, b -> b + binSize).forEach(b -> map.putIfAbsent(b,0)); 135 | return new TreeMap<>(map); 136 | } 137 | 138 | } 139 | 140 | // construct a set of histogram bins for a given set of data 141 | // the values map to a single element - the Histogram - which can then be extracted from the stream 142 | var hist = Stream.of(1,2,3,4,5,4,5,6,6,6,7,7,8,9,13) 143 | .gather(fold(() -> new Histogram(2), Histogram::putValue)) 144 | .collect(toExactlyOne()); 145 | 146 | System.out.println(hist.map()); 147 | } 148 | 149 | 150 | record Range(int min, int max) { } 151 | 152 | // not thread safe, should only be used with a sequential stream 153 | static class RangeGatheringState { 154 | 155 | private int min = Integer.MAX_VALUE; 156 | private int max = Integer.MIN_VALUE; 157 | private boolean hasGatheredValues = false; 158 | 159 | public boolean integrate(Integer value) { 160 | min = Math.min(min, value); 161 | max = Math.max(max, value); 162 | hasGatheredValues = true; 163 | return true; 164 | } 165 | 166 | public Optional range() { 167 | return hasGatheredValues ? Optional.of(new Range(min, max)) : Optional.empty(); 168 | } 169 | } 170 | 171 | private Function> toHistogramBins(int binSize) { 172 | return range -> { 173 | int lowestBin = (range.min() / binSize) * binSize; 174 | return iterate(lowestBin, b -> b <= range.max(), b -> b + binSize).boxed(); 175 | }; 176 | } 177 | 178 | @Test 179 | public void testMinMax() { 180 | 181 | // why not pass an instance of these classes to the gatherer instead of these generators and functions? 182 | // this allows us to create multiple gatherers for the same stream if it is parallelized 183 | // the runtime will create a new instance of the state for each thread 184 | 185 | final int binSize = 2; 186 | 187 | // if there are no elements found, the finisher is still called 188 | // downstream is not used by the integrator if you need to see all elements before you can continue the stream 189 | // integrator returns false if it wants to short circuit (e.g. Stream.limit()) 190 | Gatherer histogramBins = Gatherer.ofSequential( 191 | RangeGatheringState::new, 192 | (state, element, _) -> state.integrate(element), 193 | (state, downstream) -> state.range() 194 | .map(toHistogramBins(binSize)) 195 | .orElse(Stream.empty()) 196 | .forEach(downstream::push) 197 | ); 198 | 199 | // see if we can construct a set of histogram bins for a given set of data 200 | var hist = Stream.of(1,2,3,4,5,4,5,6,6,6,7,7,8,9,13) 201 | .gather(histogramBins) 202 | .toList(); 203 | 204 | System.out.println(hist); 205 | 206 | // TODO turn these into unit tests, and test case of empty inputs 207 | // hist = IntStream.of().boxed() 208 | // .gather(minMax) 209 | // .findFirst(); 210 | // 211 | // System.out.println(hist); 212 | 213 | 214 | // Stream.of(1,2,3,4,5,4,5,6,6,6,7,7,8,9,13) 215 | // .gather(minMax) 216 | // .findFirst(); 217 | // var bins = hist.map(range -> histogramBinsFromRange(range,3)) 218 | // .orElse(Stream.empty()) 219 | // .toList(); 220 | // 221 | // System.out.println(bins); 222 | 223 | 224 | } 225 | 226 | 227 | @Test 228 | public void testGatherScan() { 229 | 230 | // List numberStrings = Stream.of(1,2,3,4,5,6,7,8,9) 231 | // .gather(scan(() -> "", (string, number) -> string + number) ) 232 | // .toList(); 233 | // 234 | // System.out.println(numberStrings); 235 | 236 | // create a frequency map 237 | // the BiFunction could be extracted for readability 238 | var freqMap = Arrays.stream("gatherer".split("")) 239 | .gather(scan(HashMap::new, (map, str) -> { 240 | // Create a new map based on the previous map to avoid mutating the original one 241 | // each resulting map is emitted separately 242 | HashMap newMap = new HashMap<>(map); 243 | newMap.put(str, newMap.getOrDefault(str, 0) + 1); 244 | return newMap; 245 | })) 246 | .toList(); 247 | 248 | System.out.println(freqMap); 249 | } 250 | 251 | 252 | // We can transform a Collector to a Gatherer that emits the result downstream, 253 | // transforming terminal operations into intermediate operations 254 | public static Gatherer fromCollector(Collector collector) { 255 | 256 | Supplier supplier = collector.supplier(); 257 | BiConsumer accumulator = collector.accumulator(); 258 | BinaryOperator combiner = collector.combiner(); 259 | Function finisher = collector.finisher(); 260 | 261 | return Gatherer.of( 262 | supplier, // initializer 263 | (state, element, downstream) -> { 264 | accumulator.accept(state, element); 265 | return true; // integrator returns false if no subsequent integration is desired 266 | }, 267 | combiner, // combiner 268 | (state, downstream) -> downstream.push(finisher.apply(state)) // finisher 269 | ); 270 | } 271 | 272 | @Test 273 | public void testGatherersFromCollectors() { 274 | 275 | 276 | var words = List.of("here", "is", "a", "word", "list"); 277 | 278 | // these seem to reduce to the same thing 279 | 280 | words.stream() 281 | .gather(fromCollector(toList())) 282 | .forEach(System.out::println); 283 | 284 | words.stream() 285 | .collect(toList()) 286 | .stream() 287 | .forEach(System.out::println); 288 | 289 | 290 | // how is this different from simply using a collector and then .stream() ? 291 | // advantage is not having to create a new stream? 292 | // maybe this is more useful for other collectors or for other gatherers? 293 | // the gatherer can short circuit the stream if it wants to, but a collector MUST consume the whole stream 294 | // the gatherer MIGHT consume the whole stream, but it doesn't HAVE to, depending on the use case. 295 | // if it always consumes the whole stream, then yes it acts the same as a collector 296 | 297 | // the semantics are a little different. A gatherer is a stream operation, a collector is a terminal operation. 298 | // So while you might functionally be able to do the same thing, the intent is different. 299 | // not to mention, evaluation begins only when a terminal operation is invoked 300 | 301 | // Also a collector is N to 1, a gatherer can be N to M, 1 to N, N to 1, or 1 to 1. 302 | // A gatherer is a generalization of a collector, so overlaps in functionality for that one specific case 303 | // but a gatherer can do so much more. 304 | 305 | } 306 | } 307 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/BasicTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.lang.reflect.RecordComponent; 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | import java.util.List; 9 | import java.util.Optional; 10 | import java.util.stream.IntStream; 11 | 12 | import static org.junit.jupiter.api.Assertions.*; 13 | import static org.thinkbigthings.demo.records.Expression.*; 14 | 15 | public class BasicTest { 16 | 17 | 18 | @Test 19 | public void basicRecords() { 20 | 21 | // fields are called "record components" 22 | record MinMax(int min, int max) { } 23 | record Range(int min, int max) { } 24 | 25 | // can't assign a Range to a MinMax or cast to it (we don't have structural typing) 26 | // would need to define an interface that matches the generated methods 27 | 28 | // records can take other records as arguments 29 | record Range2D(Range x, Range y) { } 30 | 31 | // does not re-use instances like String... Maybe later? 32 | MinMax m = new MinMax(0, 0); 33 | MinMax m2 = new MinMax(0, 0); 34 | 35 | assertEquals(m, m2); 36 | } 37 | 38 | @Test 39 | public void testValidatingConstructor() { 40 | 41 | record PositiveInt(int value) { 42 | PositiveInt { 43 | // compact constructor is intended for validation 44 | // we could also assign "value" here (but not "this.value") 45 | if(value <= 0) { 46 | throw new IllegalArgumentException("Value was "+ value); 47 | } 48 | } 49 | } 50 | 51 | assertThrows(IllegalArgumentException.class, () -> new PositiveInt(-1)); 52 | 53 | assertEquals(1, new PositiveInt(1).value()); 54 | } 55 | 56 | @Test 57 | public void testImmutability() { 58 | 59 | // records are shallowly immutable 60 | record WordList(List words) { 61 | 62 | // we can assign to "this" in an overridden canonical constructor 63 | // but not in the compact constructor 64 | public WordList(List words) { 65 | this.words = Collections.unmodifiableList(words); 66 | } 67 | } 68 | 69 | ArrayList mutableWords = new ArrayList<>(); 70 | mutableWords.add("The"); 71 | mutableWords.add("fox"); 72 | mutableWords.add("jumped"); 73 | 74 | WordList list = new WordList(mutableWords); 75 | 76 | // this correctly throws an exception 77 | assertThrows(UnsupportedOperationException.class, () -> list.words().clear()); 78 | 79 | } 80 | 81 | @Test 82 | public void testDeclarations() { 83 | 84 | // We now have the ability to declare these locally: 85 | // local record classes, local enum classes, and local interfaces 86 | 87 | enum MyEnum { THIS, THAT, OTHER_THING } 88 | 89 | interface HasMyEnum { 90 | MyEnum thing(); 91 | } 92 | 93 | record EnumWrapper(MyEnum thing) implements HasMyEnum {} 94 | 95 | HasMyEnum myInterface = new EnumWrapper(MyEnum.OTHER_THING); 96 | 97 | assertEquals(MyEnum.OTHER_THING, myInterface.thing()); 98 | 99 | // Also new: an inner class can declare a member that is a record class. 100 | // To accomplish this: in Java 16 an inner class can declare a member that is explicitly or implicitly static 101 | class MyInnerClass { 102 | public EnumWrapper enumWrapper; 103 | public static String NAME = "name"; 104 | } 105 | 106 | } 107 | 108 | @Test 109 | public void testReflection() { 110 | 111 | record Reflectable(String component) {} 112 | 113 | assertTrue(Reflectable.class.isRecord()); 114 | assertFalse(this.getClass().isRecord()); 115 | 116 | RecordComponent[] recordMeta = Reflectable.class.getRecordComponents(); 117 | assertEquals(1, recordMeta.length); 118 | assertEquals("component", recordMeta[0].getName()); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/BuilderTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | public class BuilderTest { 12 | 13 | @Test 14 | public void testCustomBuilder() { 15 | 16 | BuildablePerson bilbo = BuildablePerson.newPerson() 17 | .withFirstName("Bilbo") 18 | .withLastName("Baggins"); 19 | 20 | BuildablePerson frodo = bilbo.withFirstName("Frodo"); 21 | 22 | assertEquals(bilbo.firstName(), "Bilbo"); 23 | assertEquals(frodo.firstName(), "Frodo"); 24 | assertNotEquals(bilbo, frodo); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/DtoTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.exc.ValueInstantiationException; 5 | import com.google.gson.*; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.io.*; 10 | import java.lang.reflect.Type; 11 | import java.nio.file.Paths; 12 | 13 | import static org.junit.jupiter.api.Assertions.*; 14 | 15 | public class DtoTest { 16 | 17 | @Test 18 | public void testJackson() throws Exception { 19 | 20 | String json = """ 21 | { 22 | "firstName": "Bilbo", 23 | "lastName": "Baggins" 24 | } 25 | """; 26 | 27 | record Person(String firstName, String lastName) {} 28 | 29 | Person person = new ObjectMapper().readValue(json, Person.class); 30 | 31 | assertEquals("Bilbo", person.firstName()); 32 | assertEquals("Baggins", person.lastName()); 33 | } 34 | 35 | @Test 36 | public void parseInvalidRecord() throws Exception { 37 | 38 | String json = """ 39 | { 40 | "word": "1234567890" 41 | } 42 | """; 43 | 44 | record ShortWord(String word) { 45 | ShortWord { 46 | if(word.length() > 3) { 47 | throw new IllegalArgumentException("word is too long"); 48 | } 49 | } 50 | } 51 | 52 | ObjectMapper mapper = new ObjectMapper(); 53 | 54 | // get a ValueInstantiationException caused by IllegalArgumentException 55 | // compact constructor validation is called during json parsing 56 | assertThrows(ValueInstantiationException.class, () -> mapper.readValue(json, ShortWord.class)); 57 | } 58 | 59 | // GSON has some issues, see https://github.com/google/gson/issues/1794 60 | // GSON doesn't work with inline records, so need record declaration here 61 | private static record Person(String firstName, String lastName) { } 62 | 63 | @Test 64 | void testGson() { 65 | 66 | String parsableJson = """ 67 | { 68 | "firstName": "bilbo", 69 | "lastName": "baggins" 70 | } 71 | """; 72 | 73 | JsonDeserializer personDeserializer = (JsonElement json, Type typeOfT, JsonDeserializationContext context) -> { 74 | JsonObject jObject = json.getAsJsonObject(); 75 | String firstName = jObject.get("firstName").getAsString(); 76 | String lastName = jObject.get("lastName").getAsString(); 77 | return new Person(firstName, lastName); 78 | }; 79 | 80 | Gson gson = new GsonBuilder() 81 | .registerTypeAdapter(Person.class, personDeserializer) 82 | .create(); 83 | 84 | // Test serialize 85 | Person bilbo = new Person("bilbo", "baggins"); 86 | final String personJson = gson.toJson(bilbo); 87 | assertEquals("{\"firstName\":\"bilbo\",\"lastName\":\"baggins\"}", personJson); 88 | 89 | // Test deserialize 90 | final Person parsedPerson = gson.fromJson(parsableJson, Person.class); 91 | assertEquals(bilbo, parsedPerson); 92 | assertNotSame(bilbo, parsedPerson); 93 | 94 | // test values 95 | assertEquals(bilbo.firstName(), parsedPerson.firstName()); 96 | assertEquals(bilbo.lastName(), parsedPerson.lastName()); 97 | 98 | } 99 | 100 | 101 | // static class can't be defined inside method 102 | // non-static inner class implicitly refers to its non-serializable enclosing class so would fail serialization 103 | static class PointClass implements Serializable { 104 | public float x, y; 105 | public PointClass() {} 106 | public PointClass(float x, float y) { 107 | if(x < 0 || y < 0) { 108 | throw new IllegalArgumentException("points must be > 0"); 109 | } 110 | } 111 | } 112 | 113 | @Test 114 | @DisplayName("Record serialization") 115 | public void testSerialization() throws Exception { 116 | 117 | File serializedRecord = Paths.get("build", "serial.data").toFile(); 118 | 119 | // records still have to implement Serializable to participate in serialization 120 | record Point(float x, float y) implements Serializable { 121 | Point { 122 | if(x < 0 || y < 0) { 123 | throw new IllegalArgumentException("points must be > 0"); 124 | } 125 | } 126 | } 127 | 128 | Point p1 = new Point(1, 2); 129 | 130 | try(var output = new ObjectOutputStream(new FileOutputStream(serializedRecord))) { 131 | output.writeObject(p1); 132 | } 133 | 134 | try(var input = new ObjectInputStream(new FileInputStream(serializedRecord))) { 135 | Point p2 = (Point) input.readObject(); 136 | assertEquals(p1, p2); 137 | } 138 | 139 | 140 | ////////////////////////////////// 141 | 142 | File serializedClass = Paths.get("build", "serialclass.data").toFile(); 143 | 144 | PointClass pc1 = new PointClass(1, 2); 145 | 146 | 147 | try(var output = new ObjectOutputStream(new FileOutputStream(serializedClass))) { 148 | output.writeObject(pc1); 149 | } 150 | 151 | try(var input = new ObjectInputStream(new FileInputStream(serializedClass))) { 152 | 153 | // what's wrong with traditional serialization? 154 | // Ignores accessibility (private vs public) 155 | // bypasses constructors, 156 | // can have errors at runtime for non-serializable components (not checked by compiler), 157 | // has "magic methods" (readObject etc), 158 | // possible to create impossible objects 159 | 160 | // validation in the constructor is not called 161 | // the bytes could be modified to create an "impossible" object 162 | PointClass pc2 = (PointClass) input.readObject(); 163 | 164 | assertEquals(pc1.x, pc2.x); 165 | assertEquals(pc1.y, pc2.y); 166 | assertNotEquals(pc1, pc2); 167 | } 168 | 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/JpaTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.PageImpl; 7 | import org.springframework.data.domain.PageRequest; 8 | import org.springframework.data.domain.Pageable; 9 | import org.thinkbigthings.demo.records.jpa.Store; 10 | import org.thinkbigthings.demo.records.jpa.StoreRecord; 11 | import org.thinkbigthings.demo.records.jpa.StoreRepository; 12 | 13 | import java.util.List; 14 | import java.util.Optional; 15 | 16 | import static org.junit.jupiter.api.Assertions.assertEquals; 17 | import static org.junit.jupiter.api.Assertions.assertTrue; 18 | import static org.mockito.ArgumentMatchers.any; 19 | import static org.mockito.ArgumentMatchers.eq; 20 | import static org.mockito.Mockito.mock; 21 | import static org.mockito.Mockito.when; 22 | 23 | public class JpaTest { 24 | 25 | private StoreRepository storeRepository = mock(StoreRepository.class); 26 | 27 | private Store entity = new Store("Big Store Inc", "https://bigstore.com"); 28 | private StoreRecord storeProjection = new StoreRecord(entity.getName(), entity.getWebsite()); 29 | private PageRequest requestFirstPage = PageRequest.of(0, 10); 30 | 31 | @BeforeEach 32 | public void setup() { 33 | 34 | when(storeRepository.findByName(eq(entity.getName()))).thenReturn(Optional.of(entity)); 35 | 36 | when(storeRepository.loadSummaries(any(Pageable.class))) 37 | .thenReturn(new PageImpl<>(List.of(storeProjection))); 38 | } 39 | 40 | @Test 41 | public void testReturnRecord() { 42 | 43 | Page storePage = storeRepository.loadSummaries(requestFirstPage); 44 | 45 | assertEquals(1, storePage.getTotalElements()); 46 | } 47 | 48 | @Test 49 | public void testReturnEntity() { 50 | 51 | Optional entityResults = storeRepository.findByName(entity.getName()); 52 | 53 | assertTrue(entityResults.isPresent()); 54 | assertEquals(entity.getName(), entityResults.get().getName()); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/MapKeyTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.time.Instant; 6 | import java.util.*; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | public class MapKeyTest { 11 | 12 | 13 | @Test 14 | public void testBadMultiKeyMap() { 15 | 16 | // TODO Describe how equals and hashcode are used in the implementation of HashMap 17 | Map employeeStartDates = new HashMap<>(); 18 | 19 | CustomMapKey key1 = new CustomMapKey("123", "4567"); 20 | CustomMapKey key2 = new CustomMapKey("1234", "567"); 21 | 22 | // TODO Why are these the same value? 23 | int h1 = key1.hashCode(); 24 | int h2 = key2.hashCode(); 25 | 26 | employeeStartDates.put(key1, Date.from(Instant.now())); 27 | employeeStartDates.put(key2, Date.from(Instant.now())); 28 | 29 | assertNotNull(employeeStartDates.get(key1)); 30 | 31 | // TODO why did the hashcode change? Is this an acceptable thing to do? 32 | key1.setCompany("1234"); 33 | h1 = key1.hashCode(); 34 | 35 | assertEquals(2, employeeStartDates.size()); 36 | 37 | // TODO the map knows key1 is there... why are we getting null? How could we fix this? 38 | assertNull(employeeStartDates.get(key1)); 39 | 40 | } 41 | 42 | @Test 43 | public void testMultiKeyMap() { 44 | 45 | // the key for a map must be immutable (have a consistent hashcode) 46 | // so records are a good fit 47 | record EmployeeKey(String companyId, String employeeId) {} 48 | 49 | Map employeeStartDates = new HashMap<>(); 50 | 51 | EmployeeKey k1 = new EmployeeKey("123", "4567"); 52 | EmployeeKey k2 = new EmployeeKey("1234", "567"); 53 | Date d1 = Date.from(Instant.now()); 54 | 55 | int h1 = k1.hashCode(); 56 | int h2 = k2.hashCode(); 57 | 58 | employeeStartDates.put(k1, d1); 59 | employeeStartDates.put(k2, Date.from(Instant.now())); 60 | 61 | assertEquals(2, employeeStartDates.size()); 62 | 63 | assertEquals(d1, employeeStartDates.get(k1)); 64 | 65 | assertEquals(d1, employeeStartDates.get(new EmployeeKey("123", "4567"))); 66 | 67 | } 68 | 69 | 70 | public static class CustomMapKey { 71 | 72 | private String company, employee; 73 | 74 | public CustomMapKey(String company, String employee) { 75 | this.company = company; 76 | this.employee = employee; 77 | } 78 | 79 | public String getCompany() { 80 | return company; 81 | } 82 | 83 | public void setCompany(String company) { 84 | this.company = company; 85 | } 86 | 87 | public String getEmployee() { 88 | return employee; 89 | } 90 | 91 | public void setEmployee(String employee) { 92 | this.employee = employee; 93 | } 94 | 95 | @Override 96 | public boolean equals(Object o) { 97 | if (this == o) return true; 98 | if (o == null || getClass() != o.getClass()) return false; 99 | CustomMapKey that = (CustomMapKey) o; 100 | return company.equals(that.company) && employee.equals(that.employee); 101 | } 102 | 103 | @Override 104 | public int hashCode() { 105 | return (company + employee).hashCode(); 106 | } 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/MultiReturnTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Optional; 6 | import java.util.stream.IntStream; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | import static org.thinkbigthings.demo.records.Expression.*; 10 | 11 | public class MultiReturnTest { 12 | 13 | 14 | 15 | record Statistics(int[] values, int sum, long count, double mean) {} 16 | 17 | Statistics compute(int... values) { 18 | long count = values.length; 19 | int sum = IntStream.of(values).reduce(0, Integer::sum); 20 | double mean = ((double)sum)/count; 21 | return new Statistics(values, sum, count, mean); 22 | } 23 | 24 | @Test 25 | public void testMultipleReturnValues() { 26 | 27 | // We are more likely to pass around bundles of data 28 | // if it is easy to express bundles of data. 29 | 30 | // Of course we can compute this inline, 31 | // but records give us the option to structure our logic differently. 32 | 33 | Statistics stats = compute(1, 2, 3); 34 | assertEquals(3, stats.count()); 35 | } 36 | 37 | 38 | 39 | record MultiReturn(Optional returnValue, Integer errorCode) {} 40 | 41 | public MultiReturn pretendJniWorks() { 42 | return new MultiReturn<>(Optional.of("Native value here"), 0); 43 | } 44 | 45 | public MultiReturn pretendJniError() { 46 | return new MultiReturn<>(Optional.empty(), 100); 47 | } 48 | 49 | @Test 50 | public void testSimulatedNativeMethods() { 51 | 52 | // native code often modifies arguments and uses return codes for errors 53 | // we can quickly and easily align our code more closely with native methods 54 | // handle return codes in switches, etc 55 | // of course we can wrap and throw exceptions 56 | // but records can lead us to bundle data together in ways we might not have done before 57 | 58 | var nativeError = pretendJniError(); 59 | var nativeValue = pretendJniWorks(); 60 | 61 | assertTrue(nativeValue.returnValue().isPresent()); 62 | assertFalse(nativeError.errorCode() == 0); 63 | 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/StreamTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.text.SimpleDateFormat; 6 | import java.time.Instant; 7 | import java.util.Date; 8 | import java.util.List; 9 | import java.util.Objects; 10 | 11 | import static java.util.stream.Collectors.*; 12 | import static java.util.stream.Collectors.toList; 13 | import static org.junit.jupiter.api.Assertions.assertEquals; 14 | import static org.thinkbigthings.demo.records.Functional.uncheck; 15 | import static org.thinkbigthings.demo.records.Try.*; 16 | 17 | public class StreamTest { 18 | 19 | @Test 20 | public void testRetainStreamData() { 21 | 22 | var words = List.of("here", "is", "a", "word", "list"); 23 | 24 | // map the data and pass along with original value 25 | 26 | // using "var" here allows us to assign to a real type (not Object, but anonymous) 27 | // this is allowed via LVTI introduced in Java 10, but it's... cumbersome 28 | var longWords = words.stream() 29 | .map(element -> new Object() { 30 | String word = element; 31 | int length = element.length(); 32 | Instant processedTimestamp = Instant.now(); 33 | }) 34 | .filter(t -> t.length > 3) 35 | .collect(toList()); 36 | 37 | // longWords.iterator().next(). 38 | System.out.println(longWords); 39 | 40 | // using an explicit type during processing makes the same code more readable 41 | // and we have an explicit type at the end which is easier to reason about 42 | record ProcessedWord(String word, int length, Instant recorded) {} 43 | 44 | var longWords2 = words.stream() 45 | .map(word -> new ProcessedWord(word, word.length(), Instant.now())) 46 | .filter(word -> word.length() > 3) 47 | .collect(toList()); 48 | 49 | // longWords2.iterator().next(). 50 | System.out.println(longWords2); 51 | 52 | } 53 | 54 | @Test 55 | public void testTargetTerminalOperation() { 56 | 57 | // People sometimes use Map.Entry to handle simple pairs, including inside Streams. 58 | // Records make this much more usable. 59 | 60 | record Charge(double amount, double tax) { 61 | public Charge add(Charge other){ 62 | return new Charge(amount + other.amount, tax + other.tax); 63 | } 64 | } 65 | 66 | List itemizedCharges = List.of( 67 | new Charge(2,1), 68 | new Charge(3,1), 69 | new Charge(4,1)); 70 | 71 | // one idea to get the totals, but not clear later that these values are intended to go together 72 | double totalAmount = itemizedCharges.stream() 73 | .map(Charge::amount) 74 | .reduce(0.0, Double::sum); 75 | 76 | double totalTax = itemizedCharges.stream() 77 | .map(Charge::tax) 78 | .reduce(0.0, Double::sum); 79 | 80 | // another way to get the totals 81 | // records can be a good target for reduce operations 82 | Charge total = itemizedCharges.stream() 83 | .reduce(new Charge(0,0), Charge::add); 84 | 85 | // records make a good merger for teeing operations 86 | Charge total2 = itemizedCharges.stream() 87 | .collect(teeing(summingDouble(Charge::amount), summingDouble(Charge::tax), Charge::new)); 88 | 89 | } 90 | 91 | @Test 92 | public void testStreamExceptions() { 93 | 94 | 95 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 96 | 97 | // which one won't be parsed? use this in your next coding interview 98 | List dates = List.of("2021-06-21", "whoops", "2001-12-21"); 99 | 100 | // sub-optimal approach... 101 | 102 | // code reviewers hate this one weird trick 103 | try { 104 | dates.stream() 105 | .map(uncheck(format::parse)) 106 | .collect(toList()); 107 | } 108 | catch(Exception e) { 109 | e.printStackTrace(); 110 | } 111 | 112 | 113 | // another approach 114 | 115 | // use the Try object to attempt every element in the stream 116 | // and save the exceptions and results to separate lists 117 | 118 | var tries = dates.stream() 119 | .map(tryCatch(format::parse)) 120 | .collect(toList()); 121 | 122 | // TODO wait until midnight and send this to someone's pager 123 | var exceptions = tries.stream() 124 | .map(Try::exception) 125 | .filter(Objects::nonNull) 126 | .collect(toList()); 127 | 128 | var successes = tries.stream() 129 | .map(Try::result) 130 | .filter(Objects::nonNull) 131 | .collect(toList()); 132 | 133 | 134 | // better approach 135 | 136 | record ResultsAndExceptions(List results, List exceptions) {} 137 | 138 | // records make a great merger for teeing operations 139 | ResultsAndExceptions results = dates.stream() 140 | .map(tryCatch(format::parse)) 141 | .collect(teeing( toResults(), toExceptions(), ResultsAndExceptions::new)); 142 | 143 | assertEquals(2, results.results().size()); 144 | assertEquals(1, results.exceptions().size()); 145 | 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/test/java/org/thinkbigthings/demo/records/TreeNodeTest.java: -------------------------------------------------------------------------------- 1 | package org.thinkbigthings.demo.records; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | 6 | import static org.thinkbigthings.demo.records.Expression.*; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | public class TreeNodeTest { 11 | 12 | @Test 13 | public void testASTWithSealedTypes() { 14 | 15 | // - 16 | // / \ 17 | // + 1 18 | // / \ 19 | // 5 4 20 | 21 | // (5+4) - 1 = 8 22 | Expression five = new IntExp(5); 23 | Expression four = new IntExp(4); 24 | Expression plus = new AddExp(five, four); 25 | Expression root = new SubtractExp(plus, new IntExp(1)); 26 | 27 | assertEquals(8, root.value()); 28 | } 29 | 30 | } 31 | --------------------------------------------------------------------------------