├── .gradle ├── 4.3.1 │ ├── fileChanges │ │ └── last-build.bin │ ├── fileContent │ │ └── fileContent.lock │ ├── fileHashes │ │ ├── fileHashes.bin │ │ └── fileHashes.lock │ └── taskHistory │ │ ├── taskHistory.bin │ │ └── taskHistory.lock └── buildOutputCleanup │ ├── buildOutputCleanup.lock │ ├── cache.properties │ └── outputFiles.bin ├── LICENSE ├── README.md ├── blog.png ├── build.gradle ├── build ├── libs │ └── Java11HTTP+WS.jar └── tmp │ └── jar │ └── MANIFEST.MF ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── run.png ├── settings.gradle └── src ├── main └── java │ └── com │ └── adriandavid │ ├── http │ ├── HTTPDemo.class │ ├── HTTPDemo.java │ ├── java11 │ │ ├── RESTDemo.class │ │ └── RESTDemo.java │ └── prejava11 │ │ └── RESTDemo.java │ └── ws │ └── java11 │ ├── WebSocketClient.class │ ├── WebSocketClient.java │ ├── WebSocketDemo.class │ ├── WebSocketDemo.java │ ├── WebSocketServer.class │ └── WebSocketServer.java └── test └── java ├── com └── adriandavid │ ├── http │ ├── HTTPDemo.class │ ├── HTTPDemo.java │ ├── java11 │ │ ├── RESTDemo.class │ │ └── RESTDemo.java │ └── prejava11 │ │ ├── RESTDemo.class │ │ └── RESTDemo.java │ └── ws │ └── java11 │ ├── .directory │ ├── WebSocketClient.java │ ├── WebSocketDemo.java │ └── WebSocketServer.java ├── response1.json └── response2.json /.gradle/4.3.1/fileChanges/last-build.bin: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gradle/4.3.1/fileContent/fileContent.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/4.3.1/fileContent/fileContent.lock -------------------------------------------------------------------------------- /.gradle/4.3.1/fileHashes/fileHashes.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/4.3.1/fileHashes/fileHashes.bin -------------------------------------------------------------------------------- /.gradle/4.3.1/fileHashes/fileHashes.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/4.3.1/fileHashes/fileHashes.lock -------------------------------------------------------------------------------- /.gradle/4.3.1/taskHistory/taskHistory.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/4.3.1/taskHistory/taskHistory.bin -------------------------------------------------------------------------------- /.gradle/4.3.1/taskHistory/taskHistory.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/4.3.1/taskHistory/taskHistory.lock -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/buildOutputCleanup.lock: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/buildOutputCleanup/buildOutputCleanup.lock -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/cache.properties: -------------------------------------------------------------------------------- 1 | #Mon Aug 06 23:43:04 EDT 2018 2 | gradle.version=4.3.1 3 | -------------------------------------------------------------------------------- /.gradle/buildOutputCleanup/outputFiles.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/.gradle/buildOutputCleanup/outputFiles.bin -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Adrian D. Finlay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # New Java 11 API: java.net.http 2 | Java source code example demonstrating use of the new java.net.http.* API, posted on personal blog (http://bit.ly/JavaHttp2). 3 | Built and tested with openJDK 11 EA Build 25 on Fedora Linux 28. 4 | 5 | ![alt text](https://raw.githubusercontent.com/afinlay5/Java11HttpWs/master/blog.png) 6 | 7 | # Platform 8 | - Any supporting a JVM for Java SE 11. 9 | 10 | # Requirements 11 | - Java 11. 12 | 13 | # Known Problems 14 | - None (08/07/2018). 15 | 16 | # Execution Screenshot 17 | ![alt text](https://raw.githubusercontent.com/afinlay5/Java11HttpWs/master/run.png) -------------------------------------------------------------------------------- /blog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/blog.png -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This build file was generated by the Gradle 'init' task. 3 | * 4 | * This generated file contains a commented-out sample Java project to get you started. 5 | * For more details take a look at the Java Quickstart chapter in the Gradle 6 | * user guide available at https://docs.gradle.org/4.3.1/userguide/tutorial_java_projects.html 7 | */ 8 | 9 | 10 | // Apply the java plugin to add support for Java 11 | apply plugin: 'java' 12 | 13 | // In this section you declare where to find the dependencies of your project 14 | repositories { 15 | // Use 'jcenter' for resolving your dependencies. 16 | // You can declare any Maven/Ivy/file repository here. 17 | jcenter() 18 | } -------------------------------------------------------------------------------- /build/libs/Java11HTTP+WS.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/build/libs/Java11HTTP+WS.jar -------------------------------------------------------------------------------- /build/tmp/jar/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/run.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * In a single project build this file can be empty or even removed. 6 | * 7 | * Detailed information about configuring a multi-project build in Gradle can be found 8 | * in the user guide at https://docs.gradle.org/4.3.1/userguide/multi_project_builds.html 9 | */ 10 | 11 | /* 12 | // To declare projects as part of a multi-project build use the 'include' method 13 | include 'shared' 14 | include 'api' 15 | include 'services:webservice' 16 | */ 17 | 18 | rootProject.name = 'Java11HTTP+WS' 19 | -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/http/HTTPDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/main/java/com/adriandavid/http/HTTPDemo.class -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/http/HTTPDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http; 31 | 32 | public class HTTPDemo { 33 | public static void main (String[] args) throws Exception { 34 | new com.adriandavid.http.java11.RESTDemo(args).call(); 35 | new com.adriandavid.http.prejava11.RESTDemo(args).call(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/http/java11/RESTDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/main/java/com/adriandavid/http/java11/RESTDemo.class -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/http/java11/RESTDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http.java11; 31 | 32 | 33 | import java.io.File; 34 | import java.net.URI; 35 | import java.util.Scanner; 36 | import java.time.Duration; 37 | import java.nio.file.Path; 38 | import java.nio.file.Paths; 39 | import java.nio.file.Files; 40 | import java.io.InputStream; 41 | import java.io.FileOutputStream​; 42 | import java.nio.charset.Charset; 43 | import java.net.Authenticator; 44 | import java.net.ProxySelector; 45 | import java.net.http.WebSocket; 46 | import java.net.http.HttpClient; 47 | import java.net.http.HttpRequest; 48 | import java.net.http.HttpResponse; 49 | import java.net.HttpURLConnection; 50 | import java.nio.file.StandardOpenOption; 51 | import java.nio.file.StandardCopyOption; 52 | 53 | /* HTTP GET Request, Response (Java 11 APIs) */ 54 | public class RESTDemo { 55 | private final String API_ENDPOINT = "https://onyxfx-api.herokuapp.com/nbaBasicStatBean?"; 56 | private final String API_ENDPOINT2 = "http://api.giphy.com/v1/gifs/"; 57 | private final String API_ENDPOINT2_ID = "yoJC2COHSxjIqadyZW"; 58 | private final String API_ENDPOINT2_KEY = "ZtFzb5dH6w9aYjoffJQ0RqlAsS5s0xwR"; 59 | private final HttpResponse.BodyHandler asString = HttpResponse.BodyHandlers.ofString(); 60 | private final HttpResponse.BodyHandler asDiscarded = HttpResponse.BodyHandlers.discarding(); 61 | private final HttpResponse.BodyHandler asInputStream= HttpResponse.BodyHandlers.ofInputStream(); 62 | private final HttpClient HTTP_CLIENT = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2) 63 | .followRedirects(HttpClient.Redirect.NORMAL).proxy(ProxySelector.getDefault()).build(); 64 | private String[] args; 65 | 66 | public RESTDemo (String[] args) { 67 | this.args = args; 68 | }; 69 | 70 | public void call() throws Exception { 71 | 72 | if (args.length < 4) { 73 | System.out.println("An invalid amount of arguments was supplied."); 74 | return; 75 | } 76 | 77 | System.out.println("---------------------------------"); 78 | 79 | // HTTP GET REQUEST 80 | var HTTP_REQUEST = HttpRequest.newBuilder() 81 | .uri(URI.create( //Set the appropriate endpoint 82 | new StringBuilder(API_ENDPOINT) 83 | .append("firstName=").append(args[0]) 84 | .append("&surname=").append(args[1]) 85 | .append("&season=").append(args[2]) 86 | .toString() ) ) 87 | .timeout(Duration.ofMinutes(1)) 88 | .header("Content-Type", "application/json") 89 | .build(); 90 | var HTTP_REQUEST2 = HttpRequest.newBuilder() 91 | .uri(URI.create( //Set the appropriate endpoint 92 | new StringBuilder(API_ENDPOINT2) 93 | .append(API_ENDPOINT2_ID) 94 | .append("?api_key=").append(API_ENDPOINT2_KEY) 95 | .append("&data") 96 | .append("&type") 97 | .append("&images") 98 | .toString() ) ) 99 | .timeout(Duration.ofMinutes(1)) 100 | .header("Content-Type", "application/json") 101 | .build(); 102 | 103 | 104 | // SEND HTTP GET REQUEST, RECIEVE OBJECT FOR HTTP GET RESPONSE 105 | var HTTP_RESPONSE = HTTP_CLIENT.send(HTTP_REQUEST, asString); 106 | var HTTP_RESPONSE2 = HTTP_CLIENT.send(HTTP_REQUEST, asDiscarded); 107 | var HTTP_RESPONSE3 = HTTP_CLIENT.send(HTTP_REQUEST2, asInputStream); 108 | 109 | // HTTP STATUS CODE 110 | var statusCode = HTTP_RESPONSE.statusCode(); 111 | var statusCode2 = HTTP_RESPONSE2.statusCode(); 112 | var statusCode3 = HTTP_RESPONSE3.statusCode(); 113 | 114 | 115 | // HANDLE RESPONSE 116 | if (statusCode == 200 || statusCode == 201) 117 | System.out.println("Success! -- Java 11 REST API Call\n" + 118 | args[1] + ", " + args[0] + " [" + args[3] +"]\n" + HTTP_RESPONSE.body()); 119 | else 120 | System.out.println("Failure! -- Java 11 REST API Call"); 121 | 122 | System.out.println("---------------------------------"); 123 | 124 | if (statusCode2 == 200 || statusCode2 == 201) 125 | if (HTTP_RESPONSE2.body() == null) 126 | System.out.println("Success! -- Java 11 REST API Call\n" + 127 | args[1] + ", " + args[0] + " [" + args[3] +"]\n" + "Data was discarded."); 128 | else 129 | System.out.println("Failure! -- Java 11 REST API Call"); 130 | 131 | System.out.println("---------------------------------"); 132 | 133 | if (statusCode3 == 200 || statusCode3 == 201) { 134 | System.out.println("Success! -- Java 11 REST API Call\n" + "Let's download the file! "); 135 | var HTTP_STREAM = HTTP_RESPONSE3.body(); 136 | Files.copy(HTTP_STREAM, new File("response2.json").toPath(), StandardCopyOption.REPLACE_EXISTING); 137 | HTTP_STREAM.close(); 138 | } 139 | else 140 | System.out.println("Failure! -- Java 11 REST API Call"); 141 | 142 | System.out.println("---------------------------------"); 143 | }; 144 | }; -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/http/prejava11/RESTDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http.prejava11; 31 | 32 | 33 | import java.io.File; 34 | import java.net.URI; 35 | import java.util.Scanner; 36 | import java.time.Duration; 37 | import java.nio.file.Path; 38 | import java.nio.file.Paths; 39 | import java.nio.file.Files; 40 | import java.io.InputStream; 41 | import java.io.FileOutputStream​; 42 | import java.nio.charset.Charset; 43 | import java.net.Authenticator; 44 | import java.net.ProxySelector; 45 | import java.net.http.WebSocket; 46 | import java.net.http.HttpClient; 47 | import java.net.http.HttpRequest; 48 | import java.net.http.HttpResponse; 49 | import java.net.HttpURLConnection; 50 | import java.nio.file.StandardOpenOption; 51 | import java.nio.file.StandardCopyOption; 52 | 53 | /* HTTP GET Request, Response (Pre-Java 11 API) */ 54 | public class RESTDemo { 55 | 56 | private String[] args; 57 | private final String API_ENDPOINT = "https://onyxfx-api.herokuapp.com/nbaBasicStatBean?"; 58 | private final String API_ENDPOINT2 = "http://api.giphy.com/v1/gifs/"; 59 | private final String API_ENDPOINT2_ID = "yoJC2COHSxjIqadyZW"; 60 | private final String API_ENDPOINT2_KEY = "ZtFzb5dH6w9aYjoffJQ0RqlAsS5s0xwR"; 61 | 62 | 63 | public RESTDemo (String[] args) { 64 | this.args = args; 65 | }; 66 | 67 | public void call() throws Exception { 68 | //HTTP GET REQUEST 69 | var HTTP_CLIENT= (HttpURLConnection) 70 | URI.create( 71 | new StringBuilder(API_ENDPOINT) 72 | .append("firstName=").append(args[0]) 73 | .append("&surname=").append(args[1]) 74 | .append("&season=").append(args[2]) 75 | .toString()) 76 | .toURL() 77 | .openConnection(); 78 | HTTP_CLIENT.setRequestMethod("GET"); 79 | 80 | var HTTP_CLIENT2 = (HttpURLConnection) 81 | URI.create( //Set the appropriate endpoint 82 | new StringBuilder(API_ENDPOINT2) 83 | .append(API_ENDPOINT2_ID) 84 | .append("?api_key=").append(API_ENDPOINT2_KEY) 85 | .append("&data") 86 | .append("&type") 87 | .append("&images") 88 | .toString() ) 89 | .toURL() 90 | .openConnection(); 91 | HTTP_CLIENT2.setRequestMethod("GET"); 92 | 93 | 94 | //HTTP RESPONSE 95 | var HTTP_RESPONSE = HTTP_CLIENT.getInputStream(); 96 | var scn = new Scanner(HTTP_RESPONSE); 97 | var json_sb = new StringBuilder(); 98 | while (scn.hasNext()) { 99 | json_sb.append(scn.next()); 100 | } 101 | var JSON = json_sb.toString(); 102 | 103 | if (HTTP_CLIENT2.getContentType().contains("json")) { 104 | var stream_in = (InputStream​)(HTTP_CLIENT2.getContent()); 105 | var stream_out = new FileOutputStream​ (new File("response1.json")); 106 | stream_in.transferTo(stream_out); 107 | stream_in.close(); 108 | stream_out.close(); 109 | } 110 | else 111 | return; // suffice for now. 112 | 113 | // HTTP STATUS 114 | var statusCode = HTTP_CLIENT.getResponseCode(); 115 | var statusCode2 = HTTP_CLIENT2.getResponseCode(); 116 | 117 | // HANDLE RESPONSE 118 | if (statusCode == 200 || statusCode == 201) 119 | System.out.println("Success! -- Pre-Java 11 REST API Call\n" + 120 | args[1] + ", " + args[0] + " [" + args[2] +"]\n" + JSON); 121 | else 122 | System.out.println("Failure! -- Pre-Java 11 REST API Call"); 123 | 124 | System.out.println("---------------------------------"); 125 | 126 | if (statusCode2 == 200 || statusCode2 == 201) { 127 | System.out.println("Success! -- Pre-Java 11 REST API Call\n" + "Let's download the file!" ); 128 | } 129 | else 130 | System.out.println("Failure! -- Pre-Java 11 REST API Call"); 131 | 132 | System.out.println("---------------------------------"); 133 | }; 134 | }; -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketClient.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/main/java/com/adriandavid/ws/java11/WebSocketClient.class -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.net.URI; 33 | import java.net.http.WebSocket; 34 | import java.net.http.HttpClient; 35 | import java.nio.ByteBuffer; 36 | import java.util.concurrent.CompletionStage; 37 | import java.util.concurrent.CompletableFuture; 38 | 39 | /* WebSockets in Java 11 */ 40 | public class WebSocketClient implements WebSocket.Listener { 41 | //onOpen() 42 | public void onOpen​(WebSocket webSocket) { 43 | // This WebSocket will invoke onText, onBinary, onPing, onPong or onClose methods on the associated listener (i.e. receive methods) up to n more times 44 | webSocket.request(1); 45 | System.out.println("WebSocket Listener has been opened for requests."); 46 | }; 47 | //onClose() 48 | public CompletionStage onClose​(WebSocket webSocket, int statusCode, String reason) { 49 | // The status code is an integer from the range 1000 <= code <= 65535. The reason is a string which has a UTF-8 representation not longer than 123 bytes. 50 | System.out.println("WebSocket Listener has been closed with statusCode(" + statusCode + ")."); 51 | System.out.println("Cause: " + reason); 52 | webSocket.sendClose(statusCode, reason); 53 | return new CompletableFuture(); 54 | }; 55 | //onError() 56 | public void onError​(WebSocket webSocket, Throwable error) { 57 | System.out.println("A " + error.getCause() + " exception was thrown."); 58 | System.out.println("Message: " + error.getLocalizedMessage()); 59 | webSocket.abort(); 60 | }; 61 | //onPing() 62 | public CompletionStage onPing​(WebSocket webSocket, ByteBuffer message) { 63 | webSocket.request(1); 64 | System.out.println("Ping: Client ---> Server"); 65 | System.out.println(message.asCharBuffer().toString()); 66 | return new CompletableFuture().completedFuture​("Ping completed.").thenAccept(System.out::println); 67 | }; 68 | //onPong() 69 | public CompletionStage onPong​(WebSocket webSocket, ByteBuffer message) { 70 | webSocket.request(1); 71 | System.out.println("Pong: Client ---> Server"); 72 | System.out.println(message.asCharBuffer().toString()); 73 | return new CompletableFuture().completedFuture​("Pong completed.").thenAccept(System.out::println); 74 | }; 75 | //onText() 76 | public CompletionStage onText​(WebSocket webSocket, CharSequence data, boolean last) { 77 | System.out.println(data); 78 | webSocket.request(1); 79 | return new CompletableFuture().completedFuture​("onText() completed.").thenAccept(System.out::println); 80 | }; 81 | }; -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/main/java/com/adriandavid/ws/java11/WebSocketDemo.class -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.nio.ByteBuffer; 33 | import java.nio.charset.Charset; 34 | import static java.net.http.WebSocket.NORMAL_CLOSURE; 35 | 36 | public class WebSocketDemo { 37 | 38 | public static void main (String[] args) { 39 | try { 40 | var server = new WebSocketServer().getWebSocket(); 41 | server.sendPing(ByteBuffer.wrap("Ping: Client <--- Server".getBytes(Charset.forName("UTF-16")))); 42 | server.sendPing(ByteBuffer.wrap("Pong: Client <--- Server".getBytes(Charset.forName("UTF-16")))); 43 | server.sendText("Hello!", false); 44 | server.sendClose(NORMAL_CLOSURE, "Goodbye!"); 45 | } catch (Exception e) { 46 | System.out.println("Failure:" + e.getClass().toString().replace("class", "") + " was thrown.\nMessage: " + e.getMessage()); 47 | 48 | if (e.getMessage().contains("WebSocketHandshakeException")) { 49 | var ex = ((java.net.http.WebSocketHandshakeException) e.getCause()).getResponse(); 50 | System.out.println("Body:\t" + ex.body()); 51 | System.out.println("Headers:"); 52 | ex.headers().map().forEach( (k,v)-> System.out.println("\t" + k + ": " + v)); 53 | System.out.println("HTTP request: " + ex.request()); 54 | System.out.println("HTTP version: " + ex.version()); 55 | System.out.println("Previous Reponse?: " + ex.previousResponse()); 56 | } 57 | } 58 | }; 59 | }; -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketServer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/main/java/com/adriandavid/ws/java11/WebSocketServer.class -------------------------------------------------------------------------------- /src/main/java/com/adriandavid/ws/java11/WebSocketServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.net.URI; 33 | import java.net.http.WebSocket; 34 | import java.net.http.HttpClient; 35 | import java.util.concurrent.ExecutionException; 36 | import java.util.concurrent.CompletableFuture; 37 | 38 | /* WebSockets in Java 11 */ 39 | public class WebSocketServer { 40 | private final CompletableFuture server_cf; 41 | private final WebSocket server; 42 | private final WebSocket.Listener client; 43 | // private final String ENDPOINT = "ws://127.0.0.1:8080"; // /websocket 44 | private final String ENDPOINT = "ws://localhost:8080"; // /websocket 45 | 46 | WebSocketServer () throws InterruptedException, ExecutionException { 47 | client = new WebSocketClient(); 48 | server_cf = HttpClient.newHttpClient().newWebSocketBuilder().buildAsync(URI.create(ENDPOINT), client); 49 | server = server_cf.join(); 50 | // server = server_cf.get(); 51 | } 52 | 53 | WebSocket getWebSocket() { return this.server; }; 54 | } -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/HTTPDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/test/java/com/adriandavid/http/HTTPDemo.class -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/HTTPDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http; 31 | 32 | public class HTTPDemo { 33 | public static void main (String[] args) throws Exception { 34 | new com.adriandavid.http.java11.RESTDemo(args).call(); 35 | new com.adriandavid.http.prejava11.RESTDemo(args).call(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/java11/RESTDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/test/java/com/adriandavid/http/java11/RESTDemo.class -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/java11/RESTDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http.java11; 31 | 32 | 33 | import java.io.File; 34 | import java.net.URI; 35 | import java.util.Scanner; 36 | import java.time.Duration; 37 | import java.nio.file.Path; 38 | import java.nio.file.Paths; 39 | import java.nio.file.Files; 40 | import java.io.InputStream; 41 | import java.io.FileOutputStream​; 42 | import java.nio.charset.Charset; 43 | import java.net.Authenticator; 44 | import java.net.ProxySelector; 45 | import java.net.http.WebSocket; 46 | import java.net.http.HttpClient; 47 | import java.net.http.HttpRequest; 48 | import java.net.http.HttpResponse; 49 | import java.net.HttpURLConnection; 50 | import java.nio.file.StandardOpenOption; 51 | import java.nio.file.StandardCopyOption; 52 | 53 | /* HTTP GET Request, Response (Java 11 APIs) */ 54 | public class RESTDemo { 55 | private final String API_ENDPOINT = "https://onyxfx-api.herokuapp.com/nbaBasicStatBean?"; 56 | private final String API_ENDPOINT2 = "http://api.giphy.com/v1/gifs/"; 57 | private final String API_ENDPOINT2_ID = "yoJC2COHSxjIqadyZW"; 58 | private final String API_ENDPOINT2_KEY = "ZtFzb5dH6w9aYjoffJQ0RqlAsS5s0xwR"; 59 | private final HttpResponse.BodyHandler asString = HttpResponse.BodyHandlers.ofString(); 60 | private final HttpResponse.BodyHandler asDiscarded = HttpResponse.BodyHandlers.discarding(); 61 | private final HttpResponse.BodyHandler asInputStream= HttpResponse.BodyHandlers.ofInputStream(); 62 | private final HttpClient HTTP_CLIENT = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2) 63 | .followRedirects(HttpClient.Redirect.NORMAL).proxy(ProxySelector.getDefault()).build(); 64 | private String[] args; 65 | 66 | public RESTDemo (String[] args) { 67 | this.args = args; 68 | }; 69 | 70 | public void call() throws Exception { 71 | 72 | if (args.length < 4) { 73 | System.out.println("An invalid amount of arguments was supplied."); 74 | return; 75 | } 76 | 77 | System.out.println("---------------------------------"); 78 | 79 | // HTTP GET REQUEST 80 | var HTTP_REQUEST = HttpRequest.newBuilder() 81 | .uri(URI.create( //Set the appropriate endpoint 82 | new StringBuilder(API_ENDPOINT) 83 | .append("firstName=").append(args[0]) 84 | .append("&surname=").append(args[1]) 85 | .append("&season=").append(args[2]) 86 | .toString() ) ) 87 | .timeout(Duration.ofMinutes(1)) 88 | .header("Content-Type", "application/json") 89 | .build(); 90 | var HTTP_REQUEST2 = HttpRequest.newBuilder() 91 | .uri(URI.create( //Set the appropriate endpoint 92 | new StringBuilder(API_ENDPOINT2) 93 | .append(API_ENDPOINT2_ID) 94 | .append("?api_key=").append(API_ENDPOINT2_KEY) 95 | .append("&data") 96 | .append("&type") 97 | .append("&images") 98 | .toString() ) ) 99 | .timeout(Duration.ofMinutes(1)) 100 | .header("Content-Type", "application/json") 101 | .build(); 102 | 103 | 104 | // SEND HTTP GET REQUEST, RECIEVE OBJECT FOR HTTP GET RESPONSE 105 | var HTTP_RESPONSE = HTTP_CLIENT.send(HTTP_REQUEST, asString); 106 | var HTTP_RESPONSE2 = HTTP_CLIENT.send(HTTP_REQUEST, asDiscarded); 107 | var HTTP_RESPONSE3 = HTTP_CLIENT.send(HTTP_REQUEST2, asInputStream); 108 | 109 | // HTTP STATUS CODE 110 | var statusCode = HTTP_RESPONSE.statusCode(); 111 | var statusCode2 = HTTP_RESPONSE2.statusCode(); 112 | var statusCode3 = HTTP_RESPONSE3.statusCode(); 113 | 114 | 115 | // HANDLE RESPONSE 116 | if (statusCode == 200 || statusCode == 201) 117 | System.out.println("Success! -- Java 11 REST API Call\n" + 118 | args[1] + ", " + args[0] + " [" + args[3] +"]\n" + HTTP_RESPONSE.body()); 119 | else 120 | System.out.println("Failure! -- Java 11 REST API Call"); 121 | 122 | System.out.println("---------------------------------"); 123 | 124 | if (statusCode2 == 200 || statusCode2 == 201) 125 | if (HTTP_RESPONSE2.body() == null) 126 | System.out.println("Success! -- Java 11 REST API Call\n" + 127 | args[1] + ", " + args[0] + " [" + args[3] +"]\n" + "Data was discarded."); 128 | else 129 | System.out.println("Failure! -- Java 11 REST API Call"); 130 | 131 | System.out.println("---------------------------------"); 132 | 133 | if (statusCode3 == 200 || statusCode3 == 201) { 134 | System.out.println("Success! -- Java 11 REST API Call\n" + "Let's download the file! "); 135 | var HTTP_STREAM = HTTP_RESPONSE3.body(); 136 | Files.copy(HTTP_STREAM, new File("response2.json").toPath(), StandardCopyOption.REPLACE_EXISTING); 137 | HTTP_STREAM.close(); 138 | } 139 | else 140 | System.out.println("Failure! -- Java 11 REST API Call"); 141 | 142 | System.out.println("---------------------------------"); 143 | }; 144 | }; -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/prejava11/RESTDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinlay5/Java11HttpWs/35fb8b6c33ab0e6f872313fb14842abc7ac16a74/src/test/java/com/adriandavid/http/prejava11/RESTDemo.class -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/http/prejava11/RESTDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | package com.adriandavid.http.prejava11; 31 | 32 | 33 | import java.io.File; 34 | import java.net.URI; 35 | import java.util.Scanner; 36 | import java.time.Duration; 37 | import java.nio.file.Path; 38 | import java.nio.file.Paths; 39 | import java.nio.file.Files; 40 | import java.io.InputStream; 41 | import java.io.FileOutputStream​; 42 | import java.nio.charset.Charset; 43 | import java.net.Authenticator; 44 | import java.net.ProxySelector; 45 | import java.net.http.WebSocket; 46 | import java.net.http.HttpClient; 47 | import java.net.http.HttpRequest; 48 | import java.net.http.HttpResponse; 49 | import java.net.HttpURLConnection; 50 | import java.nio.file.StandardOpenOption; 51 | import java.nio.file.StandardCopyOption; 52 | 53 | /* HTTP GET Request, Response (Pre-Java 11 API) */ 54 | public class RESTDemo { 55 | 56 | private String[] args; 57 | private final String API_ENDPOINT = "https://onyxfx-api.herokuapp.com/nbaBasicStatBean?"; 58 | private final String API_ENDPOINT2 = "http://api.giphy.com/v1/gifs/"; 59 | private final String API_ENDPOINT2_ID = "yoJC2COHSxjIqadyZW"; 60 | private final String API_ENDPOINT2_KEY = "ZtFzb5dH6w9aYjoffJQ0RqlAsS5s0xwR"; 61 | 62 | 63 | public RESTDemo (String[] args) { 64 | this.args = args; 65 | }; 66 | 67 | public void call() throws Exception { 68 | //HTTP GET REQUEST 69 | var HTTP_CLIENT= (HttpURLConnection) 70 | URI.create( 71 | new StringBuilder(API_ENDPOINT) 72 | .append("firstName=").append(args[0]) 73 | .append("&surname=").append(args[1]) 74 | .append("&season=").append(args[2]) 75 | .toString()) 76 | .toURL() 77 | .openConnection(); 78 | HTTP_CLIENT.setRequestMethod("GET"); 79 | 80 | var HTTP_CLIENT2 = (HttpURLConnection) 81 | URI.create( //Set the appropriate endpoint 82 | new StringBuilder(API_ENDPOINT2) 83 | .append(API_ENDPOINT2_ID) 84 | .append("?api_key=").append(API_ENDPOINT2_KEY) 85 | .append("&data") 86 | .append("&type") 87 | .append("&images") 88 | .toString() ) 89 | .toURL() 90 | .openConnection(); 91 | HTTP_CLIENT2.setRequestMethod("GET"); 92 | 93 | 94 | //HTTP RESPONSE 95 | var HTTP_RESPONSE = HTTP_CLIENT.getInputStream(); 96 | var scn = new Scanner(HTTP_RESPONSE); 97 | var json_sb = new StringBuilder(); 98 | while (scn.hasNext()) { 99 | json_sb.append(scn.next()); 100 | } 101 | var JSON = json_sb.toString(); 102 | 103 | if (HTTP_CLIENT2.getContentType().contains("json")) { 104 | var stream_in = (InputStream​)(HTTP_CLIENT2.getContent()); 105 | var stream_out = new FileOutputStream​ (new File("response1.json")); 106 | stream_in.transferTo(stream_out); 107 | stream_in.close(); 108 | stream_out.close(); 109 | } 110 | else 111 | return; // suffice for now. 112 | 113 | // HTTP STATUS 114 | var statusCode = HTTP_CLIENT.getResponseCode(); 115 | var statusCode2 = HTTP_CLIENT2.getResponseCode(); 116 | 117 | // HANDLE RESPONSE 118 | if (statusCode == 200 || statusCode == 201) 119 | System.out.println("Success! -- Pre-Java 11 REST API Call\n" + 120 | args[1] + ", " + args[0] + " [" + args[2] +"]\n" + JSON); 121 | else 122 | System.out.println("Failure! -- Pre-Java 11 REST API Call"); 123 | 124 | System.out.println("---------------------------------"); 125 | 126 | if (statusCode2 == 200 || statusCode2 == 201) { 127 | System.out.println("Success! -- Pre-Java 11 REST API Call\n" + "Let's download the file!" ); 128 | } 129 | else 130 | System.out.println("Failure! -- Pre-Java 11 REST API Call"); 131 | 132 | System.out.println("---------------------------------"); 133 | }; 134 | }; -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/ws/java11/.directory: -------------------------------------------------------------------------------- 1 | [Dolphin] 2 | SortRole=type 3 | Timestamp=2018,8,7,15,17,29 4 | Version=4 5 | ViewMode=1 6 | VisibleRoles=Details_text,Details_size,Details_modificationtime,Details_type,CustomizedDetails 7 | -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/ws/java11/WebSocketClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.net.URI; 33 | import java.net.http.WebSocket; 34 | import java.net.http.HttpClient; 35 | import java.nio.ByteBuffer; 36 | import java.util.concurrent.CompletionStage; 37 | import java.util.concurrent.CompletableFuture; 38 | 39 | /* WebSockets in Java 11 */ 40 | public class WebSocketClient implements WebSocket.Listener { 41 | //onOpen() 42 | public void onOpen​(WebSocket webSocket) { 43 | // This WebSocket will invoke onText, onBinary, onPing, onPong or onClose methods on the associated listener (i.e. receive methods) up to n more times 44 | webSocket.request(1); 45 | System.out.println("WebSocket Listener has been opened for requests."); 46 | }; 47 | //onClose() 48 | public CompletionStage onClose​(WebSocket webSocket, int statusCode, String reason) { 49 | // The status code is an integer from the range 1000 <= code <= 65535. The reason is a string which has a UTF-8 representation not longer than 123 bytes. 50 | System.out.println("WebSocket Listener has been closed with statusCode(" + statusCode + ")."); 51 | System.out.println("Cause: " + reason); 52 | webSocket.sendClose(statusCode, reason); 53 | return new CompletableFuture(); 54 | }; 55 | //onError() 56 | public void onError​(WebSocket webSocket, Throwable error) { 57 | System.out.println("A " + error.getCause() + " exception was thrown."); 58 | System.out.println("Message: " + error.getLocalizedMessage()); 59 | webSocket.abort(); 60 | }; 61 | //onPing() 62 | public CompletionStage onPing​(WebSocket webSocket, ByteBuffer message) { 63 | webSocket.request(1); 64 | System.out.println("Ping: Client ---> Server"); 65 | System.out.println(message.asCharBuffer().toString()); 66 | return new CompletableFuture().completedFuture​("Ping completed.").thenAccept(System.out::println); 67 | }; 68 | //onPong() 69 | public CompletionStage onPong​(WebSocket webSocket, ByteBuffer message) { 70 | webSocket.request(1); 71 | System.out.println("Pong: Client ---> Server"); 72 | System.out.println(message.asCharBuffer().toString()); 73 | return new CompletableFuture().completedFuture​("Pong completed.").thenAccept(System.out::println); 74 | }; 75 | //onText() 76 | public CompletionStage onText​(WebSocket webSocket, CharSequence data, boolean last) { 77 | System.out.println(data); 78 | webSocket.request(1); 79 | return new CompletableFuture().completedFuture​("onText() completed.").thenAccept(System.out::println); 80 | }; 81 | }; -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/ws/java11/WebSocketDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.nio.ByteBuffer; 33 | import java.nio.charset.Charset; 34 | import java.net.http.WebSocket; 35 | import static java.net.http.WebSocket.NORMAL_CLOSURE; 36 | import java.util.concurrent.CompletableFuture; 37 | 38 | public class WebSocketDemo { 39 | public static void main (String[] args) { 40 | try { 41 | var ws = new WebSocketServer(); 42 | var ws_cf = ws.getServerCf(); 43 | var socket = (WebSocket) ws_cf.get(); 44 | 45 | socket.sendPing(ByteBuffer.wrap("Ping: Client <--- Server".getBytes(Charset.forName("UTF-16")))); 46 | socket.sendPong(ByteBuffer.wrap("Pong: Client <--- Server".getBytes(Charset.forName("UTF-16")))); 47 | socket.sendText("Hello!", false); 48 | 49 | socket.sendClose(NORMAL_CLOSURE, "Goodbye!"); 50 | } catch (Exception e) { 51 | System.out.println("Failure:" + e.getClass().toString().replace("class", "") + " was thrown.\nMessage: " + e.getMessage()); 52 | 53 | if (e.getMessage().contains("WebSocketHandshakeException")) { 54 | var ex = ((java.net.http.WebSocketHandshakeException) e.getCause()).getResponse(); 55 | System.out.println("Body:\t" + ex.body()); 56 | System.out.println("Headers:"); 57 | ex.headers().map().forEach( (k,v)-> System.out.println("\t" + k + ": " + v)); 58 | System.out.println("HTTP request: " + ex.request()); 59 | System.out.println("HTTP version: " + ex.version()); 60 | System.out.println("Previous Reponse?: " + ex.previousResponse()); 61 | } 62 | 63 | System.out.println("Stack trace:"); 64 | for (var el : e.getStackTrace()) 65 | System.out.println("\t" + el); 66 | } 67 | }; 68 | }; -------------------------------------------------------------------------------- /src/test/java/com/adriandavid/ws/java11/WebSocketServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2018 Adrian D. Finlay. All rights reserved. 3 | 4 | Licensed under the MIT License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://opensource.org/licenses/MIT 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy 11 | of this software and associated documentation files (the "Software"), to deal 12 | in the Software without restriction, including without limitation the rights 13 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | copies of the Software, and to permit persons to whom the Software is 15 | furnished to do so, subject to the following conditions: 16 | 17 | The above copyright notice and this permission notice shall be included in all 18 | copies or substantial portions of the Software. 19 | 20 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | LIABILITY, WHETHER INCLUDING AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | SOFTWARE. 27 | ============================================================================== 28 | **/ 29 | 30 | // package com.adriandavid.java11.ws; 31 | 32 | import java.net.URI; 33 | import java.net.ProxySelector; 34 | import java.net.http.WebSocket; 35 | import java.net.http.HttpClient; 36 | import java.net.InetSocketAddress; 37 | import java.util.concurrent.ExecutionException; 38 | import java.util.concurrent.CompletableFuture; 39 | 40 | /* WebSockets in Java 11 */ 41 | public class WebSocketServer { 42 | private final CompletableFuture server_cf; 43 | private final String ENDPOINT = "ws://localhost:80"; // 44 | 45 | WebSocketServer () throws InterruptedException, ExecutionException { 46 | this.server_cf = HttpClient 47 | .newBuilder() 48 | .proxy(ProxySelector.of(new java.net.InetSocketAddress("localhost", 80))) 49 | .build() 50 | .newWebSocketBuilder() 51 | .subprotocols("80") 52 | .buildAsync(URI.create(ENDPOINT), new WebSocketClient()); 53 | } 54 | 55 | CompletableFuture getServerCf() { return this.server_cf; }; 56 | } -------------------------------------------------------------------------------- /src/test/java/response1.json: -------------------------------------------------------------------------------- 1 | {"data":{"type":"gif","id":"yoJC2COHSxjIqadyZW","slug":"lastweektonight-hbo-john-oliver-last-week-tonight-yoJC2COHSxjIqadyZW","url":"https:\/\/giphy.com\/gifs\/lastweektonight-hbo-john-oliver-last-week-tonight-yoJC2COHSxjIqadyZW","bitly_gif_url":"https:\/\/gph.is\/1sx2Uad","bitly_url":"https:\/\/gph.is\/1sx2Uad","embed_url":"https:\/\/giphy.com\/embed\/yoJC2COHSxjIqadyZW","username":"lastweektonight","source":"","rating":"g","content_url":"","source_tld":"","source_post_url":"","is_sticker":0,"import_datetime":"2014-11-11 16:13:36","trending_datetime":"2018-08-04 21:45:01","user":{"avatar_url":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/sKTCNdpBVOEA.gif","banner_url":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/LTmUkiB5Q2we.gif","banner_image":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/LTmUkiB5Q2we.gif","profile_url":"https:\/\/giphy.com\/lastweektonight\/","username":"lastweektonight","display_name":"Last Week Tonight with John Oliver"},"images":{"fixed_height_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_s.gif","width":"356","height":"200"},"original_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy_s.gif","width":"640","height":"360"},"fixed_width":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.gif","width":"200","height":"113","size":"320263","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.mp4","mp4_size":"41686","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.webp","webp_size":"152984"},"fixed_height_small_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100_s.gif","width":"178","height":"100"},"fixed_height_downsampled":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_d.gif","width":"356","height":"200","size":"158548","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_d.webp","webp_size":"63200"},"preview":{"width":"290","height":"162","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.mp4","mp4_size":"43464"},"fixed_height_small":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.gif","width":"178","height":"100","size":"271343","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.mp4","mp4_size":"35696","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.webp","webp_size":"133680"},"downsized_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-tumblr_s.gif","width":"500","height":"281"},"downsized":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-tumblr.gif","width":"500","height":"281","size":"1781451"},"downsized_large":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217"},"fixed_width_small_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w_s.gif","width":"100","height":"56"},"preview_webp":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.webp","width":"238","height":"134","size":"49462"},"fixed_width_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_s.gif","width":"200","height":"113"},"480w_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/480w_s.jpg","width":"480","height":"270","size":"12987"},"fixed_width_small":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.gif","width":"100","height":"56","size":"101557","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.mp4","mp4_size":"17708","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.webp","webp_size":"59734"},"downsized_small":{"width":"497","height":"280","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-downsized-small.mp4","mp4_size":"174536"},"fixed_width_downsampled":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_d.gif","width":"200","height":"113","size":"57466","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_d.webp","webp_size":"27330"},"downsized_medium":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217"},"original":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217","frames":"35","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.mp4","mp4_size":"153241","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.webp","webp_size":"999426"},"fixed_height":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.gif","width":"356","height":"200","size":"898071","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.mp4","mp4_size":"94517","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.webp","webp_size":"361558"},"looping":{"mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-loop.mp4","mp4_size":"925642"},"original_mp4":{"width":"480","height":"270","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.mp4","mp4_size":"153241"},"preview_gif":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.gif","width":"133","height":"75","size":"47662"}},"title":"happy last week tonight GIF by Last Week Tonight with John Oliver"},"meta":{"status":200,"msg":"OK","response_id":"5b6b34c571327639459137f9"}} -------------------------------------------------------------------------------- /src/test/java/response2.json: -------------------------------------------------------------------------------- 1 | {"data":{"type":"gif","id":"yoJC2COHSxjIqadyZW","slug":"lastweektonight-hbo-john-oliver-last-week-tonight-yoJC2COHSxjIqadyZW","url":"https:\/\/giphy.com\/gifs\/lastweektonight-hbo-john-oliver-last-week-tonight-yoJC2COHSxjIqadyZW","bitly_gif_url":"https:\/\/gph.is\/1sx2Uad","bitly_url":"https:\/\/gph.is\/1sx2Uad","embed_url":"https:\/\/giphy.com\/embed\/yoJC2COHSxjIqadyZW","username":"lastweektonight","source":"","rating":"g","content_url":"","source_tld":"","source_post_url":"","is_sticker":0,"import_datetime":"2014-11-11 16:13:36","trending_datetime":"2018-08-04 21:45:01","user":{"avatar_url":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/sKTCNdpBVOEA.gif","banner_url":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/LTmUkiB5Q2we.gif","banner_image":"https:\/\/media0.giphy.com\/avatars\/lastweektonight\/LTmUkiB5Q2we.gif","profile_url":"https:\/\/giphy.com\/lastweektonight\/","username":"lastweektonight","display_name":"Last Week Tonight with John Oliver"},"images":{"fixed_height_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_s.gif","width":"356","height":"200"},"original_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy_s.gif","width":"640","height":"360"},"fixed_width":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.gif","width":"200","height":"113","size":"320263","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.mp4","mp4_size":"41686","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w.webp","webp_size":"152984"},"fixed_height_small_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100_s.gif","width":"178","height":"100"},"fixed_height_downsampled":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_d.gif","width":"356","height":"200","size":"158548","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200_d.webp","webp_size":"63200"},"preview":{"width":"290","height":"162","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.mp4","mp4_size":"43464"},"fixed_height_small":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.gif","width":"178","height":"100","size":"271343","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.mp4","mp4_size":"35696","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100.webp","webp_size":"133680"},"downsized_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-tumblr_s.gif","width":"500","height":"281"},"downsized":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-tumblr.gif","width":"500","height":"281","size":"1781451"},"downsized_large":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217"},"fixed_width_small_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w_s.gif","width":"100","height":"56"},"preview_webp":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.webp","width":"238","height":"134","size":"49462"},"fixed_width_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_s.gif","width":"200","height":"113"},"480w_still":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/480w_s.jpg","width":"480","height":"270","size":"12987"},"fixed_width_small":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.gif","width":"100","height":"56","size":"101557","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.mp4","mp4_size":"17708","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/100w.webp","webp_size":"59734"},"downsized_small":{"width":"497","height":"280","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-downsized-small.mp4","mp4_size":"174536"},"fixed_width_downsampled":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_d.gif","width":"200","height":"113","size":"57466","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200w_d.webp","webp_size":"27330"},"downsized_medium":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217"},"original":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.gif","width":"640","height":"360","size":"2976217","frames":"35","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.mp4","mp4_size":"153241","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.webp","webp_size":"999426"},"fixed_height":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.gif","width":"356","height":"200","size":"898071","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.mp4","mp4_size":"94517","webp":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/200.webp","webp_size":"361558"},"looping":{"mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-loop.mp4","mp4_size":"925642"},"original_mp4":{"width":"480","height":"270","mp4":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy.mp4","mp4_size":"153241"},"preview_gif":{"url":"https:\/\/media0.giphy.com\/media\/yoJC2COHSxjIqadyZW\/giphy-preview.gif","width":"133","height":"75","size":"47662"}},"title":"happy last week tonight GIF by Last Week Tonight with John Oliver"},"meta":{"status":200,"msg":"OK","response_id":"5b6b34c571327639459137f9"}} --------------------------------------------------------------------------------