├── .gitignore ├── .idea ├── .name ├── codeStyleSettings.xml ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── CONTRIBUTING.md ├── JavaPhoenixChannels.iml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src └── main ├── java └── org │ └── phoenixframework │ └── channels │ ├── Binding.java │ ├── Channel.java │ ├── ChannelEvent.java │ ├── ChannelState.java │ ├── Envelope.java │ ├── IErrorCallback.java │ ├── IMessageCallback.java │ ├── ISocketCloseCallback.java │ ├── ISocketOpenCallback.java │ ├── ITimeoutCallback.java │ ├── Push.java │ ├── Socket.java │ ├── SocketEvent.java │ └── SocketState.java ├── resources ├── logging.properties └── sample_exchange.js └── test └── org └── phoenixframework └── channels └── SocketITest.groovy /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | JavaPhoenixChannels -------------------------------------------------------------------------------- /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 227 | 229 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ==== 3 | 4 | If you would like to contribute to the development of JavaPhoenixChannels, please submit an issue or open a pull request. Contributions of _any kind_ are always welcome: 5 | 6 | - Features 7 | - Bug Fixes 8 | - Tests 9 | - Documentation 10 | - Examples 11 | 12 | For any contribution, there are a few guidelines that need to be followed. 13 | 14 | # Submitting an Issue 15 | 16 | - Use GitHub issue search to determine if the issue has already been reported. 17 | - Submit the issue to the JavaPhoenixChannels Issues on GitHub. 18 | - Always be as helpful, inclusive and friendly as possible in the words you use. Demanding or offensive issues are very likely to be closed. 19 | - Clearly describe the steps to reproduce the issue. 20 | - Indicate the version where the issue can be reproduced. 21 | 22 | # Making Changes 23 | - Fork the JavaPhoenixChannels repository on GitHub. 24 | - Ensure an issue exists for the change you are making. 25 | - Create a branch for your fix: (`git checkout -b fix/master/my_feature_or_fix master`). 26 | - Make changes and submit a pull request for your branch in your fork. 27 | - One or more of the repository maintainers will review your change and provide feedback and/or merge your pull request. 28 | - *By submitting a change*, you agree that your work will be licensed under the license used by the project. 29 | - *Never* merge `master` into your branch, always `rebase`. 30 | 31 | # Building the Library 32 | Using Gradle 2.2.1 or later: 33 | 34 | ```shell 35 | gradle build 36 | ``` 37 | 38 | # Release and Publication 39 | In order to release, you require full contributor rights and a Bintray account with write access. 40 | 41 | ``` 42 | export BINTRAY_USER=... 43 | export BINTRAY_KEY=... 44 | gradle bintrayUpload 45 | ``` 46 | 47 | Tag the new version: 48 | ``` 49 | git tag -a v0.2.0 50 | git push origin v0.2.0 51 | ``` 52 | 53 | At this point, you have to go to the Bintray web interface and click 'publish' for the new version. 54 | 55 | -------------------------------------------------------------------------------- /JavaPhoenixChannels.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015-2016, Eoin Shanaghy 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of JavaPhoenixChannels nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATED 2 | We made [new library](https://github.com/chain-partners/kotlinphoenixchannel) in Kotlin to resolve the issues in this library. 3 | We recommend to use it : [KotlinPhoenixChannel](https://github.com/chain-partners/kotlinphoenixchannel) 4 | 5 | # Phoenix Channel Client for Java and Android 6 | 7 | JavaPhoenixChannels is a Java and Android client library for the Channels API in the [Phoenix Framework](http://www.phoenixframework.org/). Its primary purpose is to ease development of real time messaging apps for Android using an Elixir/Phoenix backend. For more about the Elixir language and the massively scalable and reliable systems you can build with Phoenix, see http://elixir-lang.org and http://www.phoenixframework.org. 8 | 9 | ## Including the Library 10 | 11 | - Add `http://dl.bintray.com/eoinsha/java-phoenix-channels` as a Maven repository 12 | - Add JavaPhoenixChannels as an app dependency: 13 | ``` 14 | dependencies { 15 | ... 16 | compile('com.github.eoinsha:JavaPhoenixChannels:0.2') { 17 | exclude module: 'groovy-all' 18 | } 19 | ``` 20 | - For Maven or Gradle-specific instructions detailing how this is done, see the "SET ME UP" section on https://bintray.com/javaphoenixchannels/java-phoenix-channels/JavaPhoenixChannels and choose "Resolving artifacts..." 21 | 22 | # Examples 23 | 24 | ## Example Android App 25 | 26 | For a full sample Android chat app, check out the repository at https://github.com/eoinsha/PhoenixChatAndroid 27 | 28 | The quick examples below are used with the [Phoenix Chat Example](https://github.com/chrismccord/phoenix_chat_example) 29 | 30 | ## Example using Groovy 31 | ```groovy 32 | import org.phoenixframework.channels.* 33 | def socket = new Socket('ws://localhost:4000/socket/websocket') 34 | socket.connect() 35 | def chan = socket.chan() 36 | chan.join("rooms:lobby", null) 37 | .receive("ignore", { -> println "IGNORE"}) 38 | .receive("ok", { envelope -> println "JOINED with $envelope" }) 39 | chan.on('new:msg', { -> println "NEW MESSAGE: $envelope"}) 40 | 41 | ``` 42 | 43 | ## Example using Java 44 | ```java 45 | import org.phoenixframework.channels.*; 46 | 47 | Socket socket; 48 | Channel channel; 49 | 50 | socket = new Socket("ws://localhost:4000/socket/websocket"); 51 | socket.connect(); 52 | 53 | channel = socket.chan("rooms:lobby", null); 54 | 55 | channel.join() 56 | .receive("ignore", new IMessageCallback() { 57 | @Override 58 | public void onMessage(Envelope envelope) { 59 | System.out.println("IGNORE"); 60 | } 61 | }) 62 | .receive("ok", new IMessageCallback() { 63 | @Override 64 | public void onMessage(Envelope envelope) { 65 | System.out.println("JOINED with " + envelope.toString()); 66 | } 67 | }); 68 | 69 | channel.on("new:msg", new IMessageCallback() { 70 | @Override 71 | public void onMessage(Envelope envelope) { 72 | System.out.println("NEW MESSAGE: " + envelope.toString()); 73 | } 74 | }); 75 | 76 | channel.on(ChannelEvent.CLOSE.getPhxEvent(), new IMessageCallback() { 77 | @Override 78 | public void onMessage(Envelope envelope) { 79 | System.out.println("CLOSED: " + envelope.toString()); 80 | } 81 | }); 82 | 83 | channel.on(ChannelEvent.ERROR.getPhxEvent(), new IMessageCallback() { 84 | @Override 85 | public void onMessage(Envelope envelope) { 86 | System.out.println("ERROR: " + envelope.toString()); 87 | } 88 | }); 89 | 90 | //Sending a message. This library uses Jackson for JSON serialization 91 | ObjectNode node = new ObjectNode(JsonNodeFactory.instance) 92 | .put("user", "my_username") 93 | .put("body", message); 94 | 95 | channel.push("new:msg", node); 96 | ``` 97 | 98 | # Contributing 99 | 100 | To contribute, see the [contribution guidelines and instructions](./CONTRIBUTING.md). 101 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.jfrog.bintray" version "1.7" 3 | } 4 | 5 | apply plugin: 'java' 6 | apply plugin: 'maven' 7 | apply plugin: 'maven-publish' 8 | apply plugin: 'groovy' 9 | if (project.hasProperty('signing.keyId')) { 10 | apply plugin: 'signing' 11 | } 12 | 13 | group = 'org.phoenixframework.channels' 14 | version = '0.2.0' 15 | 16 | allprojects { 17 | sourceCompatibility = 1.7 18 | targetCompatibility = 1.7 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | compile 'com.fasterxml.jackson.core:jackson-databind:2.8.3' 24 | compile 'com.squareup.okhttp3:okhttp:3.8.0' 25 | compile 'org.slf4j:slf4j-api:1.7.22' 26 | testCompile 'org.codehaus.groovy:groovy-all:2.3.10' 27 | testCompile "org.spockframework:spock-core:1.0-groovy-2.3" 28 | 29 | // optional dependencies for using Spock 30 | testRuntime "org.hamcrest:hamcrest-core:1.3" // only necessary if Hamcrest matchers are used 31 | testRuntime "cglib:cglib-nodep:3.1" 32 | // allows mocking of classes (in addition to interfaces) 33 | testRuntime "org.objenesis:objenesis:2.1" 34 | // allows mocking of classes without default constructor (together with CGLIB) 35 | } 36 | 37 | task javadocJar(type: Jar) { 38 | classifier = 'javadoc' 39 | from javadoc 40 | } 41 | 42 | task sourcesJar(type: Jar) { 43 | classifier = 'sources' 44 | from sourceSets.main.allSource 45 | } 46 | 47 | repositories { 48 | mavenCentral() 49 | } 50 | 51 | artifacts { 52 | archives javadocJar, sourcesJar 53 | } 54 | 55 | if (project.hasProperty('signing.keyId')) { 56 | signing { 57 | sign configurations.archives 58 | } 59 | } 60 | 61 | publishing { 62 | publications { 63 | JavaPhoenixChannelsJar(MavenPublication) { 64 | from components.java 65 | groupId 'com.github.eoinsha' 66 | artifactId 'JavaPhoenixChannels' 67 | version '0.2' 68 | } 69 | } 70 | } 71 | 72 | bintray { 73 | user = System.getenv('BINTRAY_USER') 74 | key = System.getenv('BINTRAY_KEY') 75 | pkg { 76 | repo = 'java-phoenix-channels' 77 | name = 'JavaPhoenixChannels' 78 | userOrg = 'javaphoenixchannels' 79 | licenses = ['BSD-3'] 80 | vcsUrl = 'https://github.com/eoinsha/JavaPhoenixChannels.git' 81 | } 82 | publications = ['JavaPhoenixChannelsJar'] 83 | } 84 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LEECHHE/JavaPhoenixChannels/9b47f1837163ae9dbd6e8ecba6a24c562fd2f523/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Sep 15 10:09:43 CEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /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 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 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 %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="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 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/Binding.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | class Binding { 4 | private final String event; 5 | private final IMessageCallback callback; 6 | 7 | public Binding(final String event, final IMessageCallback callback) { 8 | this.event = event; 9 | this.callback = callback; 10 | } 11 | 12 | public String getEvent() { 13 | return event; 14 | } 15 | 16 | public IMessageCallback getCallback() { 17 | return callback; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "Binding{" + 23 | "event='" + event + '\'' + 24 | ", callback=" + callback + 25 | '}'; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/Channel.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | 5 | import java.io.IOException; 6 | import java.util.ArrayList; 7 | import java.util.Iterator; 8 | import java.util.List; 9 | import java.util.Timer; 10 | import java.util.TimerTask; 11 | import java.util.concurrent.LinkedBlockingDeque; 12 | 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | /** 17 | * Encapsulation of a Phoenix channel: a Socket, a topic and the channel's state. 18 | */ 19 | public class Channel { 20 | 21 | private static final long DEFAULT_TIMEOUT = 5000; 22 | 23 | private static final Logger log = LoggerFactory.getLogger(Channel.class); 24 | 25 | private final List bindings = new ArrayList<>(); 26 | 27 | private Timer channelTimer = null; 28 | 29 | private final Push joinPush; 30 | 31 | private boolean joinedOnce = false; 32 | 33 | private final JsonNode payload; 34 | 35 | private final LinkedBlockingDeque pushBuffer = new LinkedBlockingDeque<>(); 36 | 37 | private final Socket socket; 38 | 39 | private ChannelState state = ChannelState.CLOSED; 40 | 41 | private final String topic; 42 | 43 | public Channel(final String topic, final JsonNode payload, final Socket socket) { 44 | this.topic = topic; 45 | this.payload = payload; 46 | this.socket = socket; 47 | this.joinPush = new Push(this, ChannelEvent.JOIN.getPhxEvent(), payload, DEFAULT_TIMEOUT); 48 | this.channelTimer = new Timer("Phx Rejoin timer for " + topic); 49 | 50 | this.joinPush.receive("ok", new IMessageCallback() { 51 | @Override 52 | public void onMessage(Envelope envelope) { 53 | Channel.this.state = ChannelState.JOINED; 54 | } 55 | }); 56 | 57 | this.joinPush.timeout(new ITimeoutCallback() { 58 | @Override 59 | public void onTimeout() { 60 | Channel.this.state = ChannelState.ERRORED; 61 | } 62 | }); 63 | 64 | this.onClose(new IMessageCallback() { 65 | @Override 66 | public void onMessage(Envelope envelope) { 67 | Channel.this.state = ChannelState.CLOSED; 68 | Channel.this.socket.remove(Channel.this); 69 | } 70 | }); 71 | this.onError(new IErrorCallback() { 72 | @Override 73 | public void onError(Throwable t) { 74 | Channel.this.state = ChannelState.ERRORED; 75 | scheduleRejoinTimer(); 76 | } 77 | }); 78 | this.on(ChannelEvent.REPLY.getPhxEvent(), new IMessageCallback() { 79 | @Override 80 | public void onMessage(final Envelope envelope) { 81 | Channel.this.trigger(Socket.replyEventName(envelope.getRef()), envelope); 82 | } 83 | }); 84 | 85 | 86 | } 87 | 88 | /** 89 | * @return true if the socket is open and the channel has joined 90 | */ 91 | private boolean canPush() { 92 | return this.socket.isConnected() && this.state == ChannelState.JOINED; 93 | } 94 | 95 | public Socket getSocket() { 96 | return socket; 97 | } 98 | 99 | public String getTopic() { 100 | return topic; 101 | } 102 | 103 | public boolean isMember(final String topic) { 104 | return this.topic.equals(topic); 105 | } 106 | 107 | /** 108 | * Initiates a channel join event 109 | * 110 | * @return This Push instance 111 | * @throws IllegalStateException Thrown if the channel has already been joined 112 | * @throws IOException Thrown if the join could not be sent 113 | */ 114 | public Push join() throws IllegalStateException, IOException { 115 | if (this.joinedOnce) { 116 | throw new IllegalStateException( 117 | "Tried to join multiple times. 'join' can only be invoked once per channel"); 118 | } 119 | this.joinedOnce = true; 120 | this.sendJoin(); 121 | return this.joinPush; 122 | } 123 | 124 | public Push leave() throws IOException { 125 | return this.push(ChannelEvent.LEAVE.getPhxEvent()).receive("ok", new IMessageCallback() { 126 | public void onMessage(final Envelope envelope) { 127 | Channel.this.trigger(ChannelEvent.CLOSE.getPhxEvent(), null); 128 | } 129 | }); 130 | } 131 | 132 | /** 133 | * Unsubscribe for event notifications 134 | * 135 | * @param event The event name 136 | * @return The instance's self 137 | */ 138 | public Channel off(final String event) { 139 | synchronized (bindings) { 140 | for (final Iterator bindingIter = bindings.iterator(); 141 | bindingIter.hasNext(); ) { 142 | if (bindingIter.next().getEvent().equals(event)) { 143 | bindingIter.remove(); 144 | break; 145 | } 146 | } 147 | } 148 | return this; 149 | } 150 | 151 | /** 152 | * @param event The event name 153 | * @param callback The callback to be invoked with the event's message 154 | * @return The instance's self 155 | */ 156 | public Channel on(final String event, final IMessageCallback callback) { 157 | synchronized (bindings) { 158 | this.bindings.add(new Binding(event, callback)); 159 | } 160 | return this; 161 | } 162 | 163 | private void onClose(final IMessageCallback callback) { 164 | this.on(ChannelEvent.CLOSE.getPhxEvent(), callback); 165 | } 166 | 167 | /** 168 | * Register an error callback for the channel 169 | * 170 | * @param callback Callback to be invoked on error 171 | */ 172 | private void onError(final IErrorCallback callback) { 173 | this.on(ChannelEvent.ERROR.getPhxEvent(), new IMessageCallback() { 174 | @Override 175 | public void onMessage(final Envelope envelope) { 176 | String reason = null; 177 | if (envelope != null) { 178 | reason = envelope.getReason(); 179 | } 180 | callback.onError(new IOException(reason)); 181 | } 182 | }); 183 | } 184 | 185 | /** 186 | * Pushes a payload to be sent to the channel 187 | * 188 | * @param event The event name 189 | * @param payload The message payload 190 | * @param timeout The number of milliseconds to wait before triggering a timeout 191 | * @return The Push instance used to send the message 192 | * @throws IOException Thrown if the payload cannot be pushed 193 | * @throws IllegalStateException Thrown if the channel has not yet been joined 194 | */ 195 | private Push push(final String event, final JsonNode payload, final long timeout) 196 | throws IOException, IllegalStateException { 197 | if (!this.joinedOnce) { 198 | throw new IllegalStateException("Unable to push event before channel has been joined"); 199 | } 200 | final Push pushEvent = new Push(this, event, payload, timeout); 201 | if (this.canPush()) { 202 | pushEvent.send(); 203 | } else { 204 | this.pushBuffer.add(pushEvent); 205 | } 206 | return pushEvent; 207 | } 208 | 209 | public Push push(final String event, final JsonNode payload) throws IOException { 210 | return push(event, payload, DEFAULT_TIMEOUT); 211 | } 212 | 213 | public Push push(final String event) throws IOException { 214 | return push(event, null); 215 | } 216 | 217 | private void rejoin() throws IOException { 218 | this.sendJoin(); 219 | while (!this.pushBuffer.isEmpty()) { 220 | this.pushBuffer.removeFirst().send(); 221 | } 222 | } 223 | 224 | private void rejoinUntilConnected() throws IOException { 225 | if (this.state == ChannelState.ERRORED) { 226 | if (this.socket.isConnected()) { 227 | this.rejoin(); 228 | } else { 229 | scheduleRejoinTimer(); 230 | } 231 | } 232 | } 233 | 234 | public void scheduleRepeatingTask(TimerTask timerTask, long ms) { 235 | this.channelTimer.schedule(timerTask, ms, ms); 236 | } 237 | 238 | public void scheduleTask(TimerTask timerTask, long ms) { 239 | this.channelTimer.schedule(timerTask, ms); 240 | } 241 | 242 | @Override 243 | public String toString() { 244 | return "Channel{" + 245 | "topic='" + topic + '\'' + 246 | ", message=" + payload + 247 | ", bindings(" + bindings.size() + ")=" + bindings + 248 | '}'; 249 | } 250 | 251 | /** 252 | * Triggers event signalling to all callbacks bound to the specified event. 253 | * Do not call this method except for testing and {@link Socket}. 254 | * 255 | * @param triggerEvent The event name 256 | * @param envelope The message's envelope relating to the event or null if not relevant. 257 | */ 258 | public void trigger(final String triggerEvent, final Envelope envelope) { 259 | synchronized (bindings) { 260 | for (final Binding binding : bindings) { 261 | if (binding.getEvent().equals(triggerEvent)) { 262 | // Channel Events get the full envelope 263 | binding.getCallback().onMessage(envelope); 264 | break; 265 | } 266 | } 267 | } 268 | } 269 | 270 | private void scheduleRejoinTimer() { 271 | final TimerTask rejoinTimerTask = new TimerTask() { 272 | @Override 273 | public void run() { 274 | try { 275 | Channel.this.rejoinUntilConnected(); 276 | } catch (IOException e) { 277 | log.error("Failed to rejoin", e); 278 | } 279 | } 280 | }; 281 | scheduleTask(rejoinTimerTask, Socket.RECONNECT_INTERVAL_MS); 282 | } 283 | 284 | private void sendJoin() throws IOException { 285 | this.state = ChannelState.JOINING; 286 | this.joinPush.send(); 287 | } 288 | 289 | 290 | } 291 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/ChannelEvent.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public enum ChannelEvent { 4 | CLOSE("phx_close"), 5 | ERROR("phx_error"), 6 | JOIN("phx_join"), 7 | REPLY("phx_reply"), 8 | LEAVE("phx_leave"); 9 | 10 | private final String phxEvent; 11 | 12 | public static ChannelEvent getEvent(final String phxEvent) { 13 | for (final ChannelEvent ev : values()) { 14 | if (ev.getPhxEvent().equals(phxEvent)) { 15 | return ev; 16 | } 17 | } 18 | return null; 19 | } 20 | 21 | ChannelEvent(final String phxEvent) { 22 | this.phxEvent = phxEvent; 23 | } 24 | 25 | public String getPhxEvent() { 26 | return phxEvent; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/ChannelState.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public enum ChannelState { 4 | CLOSED, 5 | ERRORED, 6 | JOINED, 7 | JOINING 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/Envelope.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | 4 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 5 | import com.fasterxml.jackson.annotation.JsonProperty; 6 | import com.fasterxml.jackson.databind.JsonNode; 7 | 8 | // To fix UnrecognizedPropertyException. 9 | @JsonIgnoreProperties(ignoreUnknown = true) 10 | public class Envelope { 11 | @JsonProperty(value = "topic") 12 | private String topic; 13 | 14 | @JsonProperty(value = "event") 15 | private String event; 16 | 17 | @JsonProperty(value = "payload") 18 | private JsonNode payload; 19 | 20 | @JsonProperty(value = "ref") 21 | private String ref; 22 | 23 | @SuppressWarnings("unused") 24 | public Envelope() { 25 | } 26 | 27 | public Envelope(final String topic, final String event, final JsonNode payload, final String ref) { 28 | this.topic = topic; 29 | this.event = event; 30 | this.payload = payload; 31 | this.ref = ref; 32 | } 33 | 34 | public String getTopic() { 35 | return topic; 36 | } 37 | 38 | public String getEvent() { 39 | return event; 40 | } 41 | 42 | public JsonNode getPayload() { 43 | return payload; 44 | } 45 | 46 | /** 47 | * Helper to retrieve the value of "ref" from the payload 48 | * 49 | * @return The ref string or null if not found 50 | */ 51 | public String getRef() { 52 | if (ref != null) return ref; 53 | final JsonNode refNode = payload.get("ref"); 54 | return refNode != null ? refNode.textValue() : null; 55 | } 56 | 57 | /** 58 | * Helper to retrieve the value of "status" from the payload 59 | * 60 | * @return The status string or null if not found 61 | */ 62 | public String getResponseStatus() { 63 | final JsonNode statusNode = payload.get("status"); 64 | return statusNode == null ? null : statusNode.textValue(); 65 | } 66 | 67 | /** 68 | * Helper to retrieve the value of "reason" from the payload 69 | * 70 | * @return The reason string or null if not found 71 | */ 72 | public String getReason() { 73 | final JsonNode reasonNode = payload.get("reason"); 74 | return reasonNode == null ? null : reasonNode.textValue(); 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "Envelope{" + 80 | "topic='" + topic + '\'' + 81 | ", event='" + event + '\'' + 82 | ", payload=" + payload + 83 | '}'; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/IErrorCallback.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public interface IErrorCallback { 4 | void onError(final Throwable t); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/IMessageCallback.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public interface IMessageCallback { 4 | 5 | /** 6 | * @param envelope The envelope containing the message payload and properties 7 | */ 8 | void onMessage(final Envelope envelope); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/ISocketCloseCallback.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public interface ISocketCloseCallback { 4 | void onClose(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/ISocketOpenCallback.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public interface ISocketOpenCallback { 4 | void onOpen(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/ITimeoutCallback.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public interface ITimeoutCallback { 4 | void onTimeout(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/Push.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | 5 | import java.io.IOException; 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.TimerTask; 11 | 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | public class Push { 16 | 17 | private static final Logger log = LoggerFactory.getLogger(Push.class); 18 | 19 | private class TimeoutHook { 20 | 21 | private ITimeoutCallback callback; 22 | 23 | private final long ms; 24 | 25 | private TimerTask timerTask; 26 | 27 | public TimeoutHook(final long ms) { 28 | this.ms = ms; 29 | } 30 | 31 | public ITimeoutCallback getCallback() { 32 | return callback; 33 | } 34 | 35 | public long getMs() { 36 | return ms; 37 | } 38 | 39 | public TimerTask getTimerTask() { 40 | return timerTask; 41 | } 42 | 43 | public boolean hasCallback() { 44 | return this.callback != null; 45 | } 46 | 47 | public void setCallback(final ITimeoutCallback callback) { 48 | this.callback = callback; 49 | } 50 | 51 | public void setTimerTask(final TimerTask timerTask) { 52 | this.timerTask = timerTask; 53 | } 54 | } 55 | 56 | private Channel channel = null; 57 | 58 | private String event = null; 59 | 60 | private JsonNode payload = null; 61 | 62 | private final Map> recHooks = new HashMap<>(); 63 | 64 | private Envelope receivedEnvelope = null; 65 | 66 | private String refEvent = null; 67 | 68 | private boolean sent = false; 69 | 70 | private final TimeoutHook timeoutHook; 71 | 72 | Push(final Channel channel, final String event, final JsonNode payload, final long timeout) { 73 | this.channel = channel; 74 | this.event = event; 75 | this.payload = payload; 76 | this.timeoutHook = new TimeoutHook(timeout); 77 | } 78 | 79 | /** 80 | * Registers for notifications on status messages 81 | * 82 | * @param status The message status to register callbacks on 83 | * @param callback The callback handler 84 | * @return This instance's self 85 | */ 86 | public Push receive(final String status, final IMessageCallback callback) { 87 | if (this.receivedEnvelope != null) { 88 | final String receivedStatus = this.receivedEnvelope.getResponseStatus(); 89 | if (receivedStatus != null && receivedStatus.equals(status)) { 90 | callback.onMessage(this.receivedEnvelope); 91 | } 92 | } 93 | synchronized (recHooks) { 94 | List statusHooks = this.recHooks.get(status); 95 | if (statusHooks == null) { 96 | statusHooks = new ArrayList<>(); 97 | this.recHooks.put(status, statusHooks); 98 | } 99 | statusHooks.add(callback); 100 | } 101 | 102 | return this; 103 | } 104 | 105 | /** 106 | * Registers for notification of message response timeout 107 | * 108 | * @param callback The callback handler called when timeout is reached 109 | * @return This instance's self 110 | */ 111 | public Push timeout(final ITimeoutCallback callback) { 112 | if (this.timeoutHook.hasCallback()) { 113 | throw new IllegalStateException("Only a single after hook can be applied to a Push"); 114 | } 115 | 116 | this.timeoutHook.setCallback(callback); 117 | 118 | return this; 119 | } 120 | 121 | Channel getChannel() { 122 | return channel; 123 | } 124 | 125 | String getEvent() { 126 | return event; 127 | } 128 | 129 | JsonNode getPayload() { 130 | return payload; 131 | } 132 | 133 | Map> getRecHooks() { 134 | return recHooks; 135 | } 136 | 137 | Envelope getReceivedEnvelope() { 138 | return receivedEnvelope; 139 | } 140 | 141 | boolean isSent() { 142 | return sent; 143 | } 144 | 145 | void send() throws IOException { 146 | final String ref = channel.getSocket().makeRef(); 147 | log.trace("Push send, ref={}", ref); 148 | 149 | this.refEvent = Socket.replyEventName(ref); 150 | this.receivedEnvelope = null; 151 | 152 | this.channel.on(this.refEvent, new IMessageCallback() { 153 | @Override 154 | public void onMessage(final Envelope envelope) { 155 | Push.this.receivedEnvelope = envelope; 156 | Push.this.matchReceive(receivedEnvelope.getResponseStatus(), envelope); 157 | Push.this.cancelRefEvent(); 158 | Push.this.cancelTimeout(); 159 | } 160 | }); 161 | 162 | this.startTimeout(); 163 | this.sent = true; 164 | final Envelope envelope = new Envelope(this.channel.getTopic(), this.event, this.payload, ref); 165 | this.channel.getSocket().push(envelope); 166 | } 167 | 168 | private void cancelRefEvent() { 169 | this.channel.off(this.refEvent); 170 | } 171 | 172 | private void cancelTimeout() { 173 | this.timeoutHook.getTimerTask().cancel(); 174 | this.timeoutHook.setTimerTask(null); 175 | } 176 | 177 | private TimerTask createTimerTask() { 178 | final Runnable callback = new Runnable() { 179 | @Override 180 | public void run() { 181 | Push.this.cancelRefEvent(); 182 | if (Push.this.timeoutHook.hasCallback()) { 183 | Push.this.timeoutHook.getCallback().onTimeout(); 184 | } 185 | } 186 | }; 187 | 188 | return new TimerTask() { 189 | @Override 190 | public void run() { 191 | callback.run(); 192 | } 193 | }; 194 | } 195 | 196 | /** 197 | * Visible for testing. Do not call it except for {@link Push}. 198 | */ 199 | public void matchReceive(final String status, final Envelope envelope) { 200 | synchronized (recHooks) { 201 | final List statusCallbacks = this.recHooks.get(status); 202 | if (statusCallbacks != null) { 203 | for (final IMessageCallback callback : statusCallbacks) { 204 | callback.onMessage(envelope); 205 | } 206 | } 207 | } 208 | } 209 | 210 | private void startTimeout() { 211 | this.timeoutHook.setTimerTask(createTimerTask()); 212 | this.channel.scheduleTask(this.timeoutHook.getTimerTask(), this.timeoutHook.getMs()); 213 | } 214 | } -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/Socket.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.databind.node.JsonNodeFactory; 6 | import com.fasterxml.jackson.databind.node.ObjectNode; 7 | 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | import java.util.Collections; 11 | import java.util.HashMap; 12 | import java.util.Iterator; 13 | import java.util.List; 14 | import java.util.Set; 15 | import java.util.Timer; 16 | import java.util.TimerTask; 17 | import java.util.concurrent.LinkedBlockingQueue; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import okhttp3.MediaType; 23 | import okhttp3.OkHttpClient; 24 | import okhttp3.Request; 25 | import okhttp3.RequestBody; 26 | import okhttp3.Response; 27 | import okhttp3.WebSocket; 28 | import okhttp3.WebSocketListener; 29 | import okio.ByteString; 30 | 31 | public class Socket { 32 | 33 | private static final Logger log = LoggerFactory.getLogger(Socket.class); 34 | 35 | public class PhoenixWSListener extends WebSocketListener { 36 | 37 | @Override 38 | public void onOpen(WebSocket webSocket, Response response) { 39 | log.trace("WebSocket onOpen: {}", webSocket); 40 | Socket.this.webSocket = webSocket; 41 | cancelReconnectTimer(); 42 | 43 | startHeartbeatTimer(); 44 | 45 | for (final ISocketOpenCallback callback : socketOpenCallbacks) { 46 | callback.onOpen(); 47 | } 48 | 49 | Socket.this.flushSendBuffer(); 50 | } 51 | 52 | @Override 53 | public void onMessage(WebSocket webSocket, String text) { 54 | log.trace("onMessage: {}", text); 55 | 56 | try { 57 | final Envelope envelope = objectMapper.readValue(text, Envelope.class); 58 | synchronized (channels) { 59 | for (final Channel channel : channels) { 60 | if (channel.isMember(envelope.getTopic())) { 61 | channel.trigger(envelope.getEvent(), envelope); 62 | } 63 | } 64 | } 65 | 66 | for (final IMessageCallback callback : messageCallbacks) { 67 | callback.onMessage(envelope); 68 | } 69 | } catch (IOException e) { 70 | log.error("Failed to read message payload", e); 71 | } 72 | } 73 | 74 | @Override 75 | public void onMessage(WebSocket webSocket, ByteString bytes) { 76 | onMessage(webSocket, bytes.toString()); 77 | } 78 | 79 | @Override 80 | public void onClosing(WebSocket webSocket, int code, String reason) { 81 | } 82 | 83 | @Override 84 | public void onClosed(WebSocket webSocket, int code, String reason) { 85 | log.trace("WebSocket onClose {}/{}", code, reason); 86 | Socket.this.webSocket = null; 87 | 88 | for (final ISocketCloseCallback callback : socketCloseCallbacks) { 89 | callback.onClose(); 90 | } 91 | } 92 | 93 | @Override 94 | public void onFailure(WebSocket webSocket, Throwable t, Response response) { 95 | log.warn("WebSocket connection error", t); 96 | try { 97 | //TODO if there are multiple errorCallbacks do we really want to trigger 98 | //the same channel error callbacks multiple times? 99 | triggerChannelError(); 100 | for (final IErrorCallback callback : errorCallbacks) { 101 | callback.onError(t); 102 | } 103 | } finally { 104 | // Assume closed on failure 105 | if (Socket.this.webSocket != null) { 106 | try { 107 | Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received"); 108 | } finally { 109 | Socket.this.webSocket = null; 110 | } 111 | } 112 | if (reconnectOnFailure) { 113 | scheduleReconnectTimer(); 114 | } 115 | } 116 | } 117 | } 118 | 119 | public static final int RECONNECT_INTERVAL_MS = 5000; 120 | 121 | private static final int DEFAULT_HEARTBEAT_INTERVAL = 7000; 122 | 123 | private final List channels = new ArrayList<>(); 124 | 125 | private String endpointUri = null; 126 | 127 | private final Set errorCallbacks = Collections.newSetFromMap(new HashMap()); 128 | 129 | private final int heartbeatInterval; 130 | 131 | private TimerTask heartbeatTimerTask = null; 132 | 133 | private final OkHttpClient httpClient; 134 | 135 | private final Set messageCallbacks = Collections.newSetFromMap(new HashMap()); 136 | 137 | private final ObjectMapper objectMapper = new ObjectMapper(); 138 | 139 | private boolean reconnectOnFailure = true; 140 | 141 | private TimerTask reconnectTimerTask = null; 142 | 143 | private int refNo = 1; 144 | 145 | private final LinkedBlockingQueue sendBuffer = new LinkedBlockingQueue<>(); 146 | 147 | private final Set socketCloseCallbacks = Collections 148 | .newSetFromMap(new HashMap()); 149 | 150 | private final Set socketOpenCallbacks = Collections 151 | .newSetFromMap(new HashMap()); 152 | 153 | private Timer timer = null; 154 | 155 | private WebSocket webSocket = null; 156 | 157 | /** 158 | * Builder class for {@link Socket}. 159 | */ 160 | public static class Builder { 161 | 162 | private final String endpointUri; 163 | private Integer heartbeatIntervalInMs; 164 | private OkHttpClient httpClient; 165 | 166 | public Builder(final String endpointUri) { 167 | this.endpointUri = endpointUri; 168 | } 169 | 170 | public Builder setHeartbeatIntervalInMs(final int heartbeatIntervalInMs) { 171 | this.heartbeatIntervalInMs = heartbeatIntervalInMs; 172 | return this; 173 | } 174 | 175 | public Builder setHttpClient(final OkHttpClient httpBuilder) { 176 | this.httpClient = httpBuilder; 177 | return this; 178 | } 179 | 180 | public Socket build() { 181 | return new Socket(endpointUri, 182 | heartbeatIntervalInMs == null ? DEFAULT_HEARTBEAT_INTERVAL : heartbeatIntervalInMs, 183 | httpClient == null ? new OkHttpClient() : httpClient); 184 | } 185 | } 186 | 187 | /** 188 | * Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration 189 | * methods. 190 | */ 191 | private final PhoenixWSListener wsListener = new PhoenixWSListener(); 192 | 193 | public Socket(final String endpointUri) throws IOException { 194 | this(endpointUri, DEFAULT_HEARTBEAT_INTERVAL); 195 | } 196 | 197 | public Socket(final String endpointUri, final int heartbeatIntervalInMs) { 198 | this(endpointUri, heartbeatIntervalInMs, new OkHttpClient()); 199 | } 200 | 201 | public Socket(final String endpointUri, final int heartbeatIntervalInMs, final OkHttpClient httpClient) { 202 | log.trace("PhoenixSocket({})", endpointUri); 203 | this.endpointUri = endpointUri; 204 | this.heartbeatInterval = heartbeatIntervalInMs; 205 | this.httpClient = httpClient; 206 | this.timer = new Timer("Reconnect Timer for " + endpointUri); 207 | } 208 | 209 | /** 210 | * Retrieve a channel instance for the specified topic 211 | * 212 | * @param topic The channel topic 213 | * @param payload The message payload 214 | * @return A Channel instance to be used for sending and receiving events for the topic 215 | */ 216 | public Channel chan(final String topic, final JsonNode payload) { 217 | log.trace("chan: {}, {}", topic, payload); 218 | final Channel channel = new Channel(topic, payload, Socket.this); 219 | synchronized (channels) { 220 | channels.add(channel); 221 | } 222 | return channel; 223 | } 224 | 225 | public void connect() throws IOException { 226 | log.trace("connect"); 227 | disconnect(); 228 | // No support for ws:// or ws:// in okhttp. See https://github.com/square/okhttp/issues/1652 229 | final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:") 230 | .replaceFirst("^wss:", "https:"); 231 | final Request request = new Request.Builder().url(httpUrl).build(); 232 | webSocket = httpClient.newWebSocket(request, wsListener); 233 | } 234 | 235 | public void disconnect() throws IOException { 236 | log.trace("disconnect"); 237 | if (webSocket != null) { 238 | webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client"); 239 | } 240 | cancelHeartbeatTimer(); 241 | cancelReconnectTimer(); 242 | } 243 | 244 | /** 245 | * @return true if the socket connection is connected 246 | */ 247 | public boolean isConnected() { 248 | return webSocket != null; 249 | } 250 | 251 | /** 252 | * Register a callback for SocketEvent.ERROR events 253 | * 254 | * @param callback The callback to receive CLOSE events 255 | * @return This Socket instance 256 | */ 257 | public Socket onClose(final ISocketCloseCallback callback) { 258 | this.socketCloseCallbacks.add(callback); 259 | return this; 260 | } 261 | 262 | /** 263 | * Register a callback for SocketEvent.ERROR events 264 | * 265 | * @param callback The callback to receive ERROR events 266 | * @return This Socket instance 267 | */ 268 | public Socket onError(final IErrorCallback callback) { 269 | this.errorCallbacks.add(callback); 270 | return this; 271 | } 272 | 273 | /** 274 | * Register a callback for SocketEvent.MESSAGE events 275 | * 276 | * @param callback The callback to receive MESSAGE events 277 | * @return This Socket instance 278 | */ 279 | public Socket onMessage(final IMessageCallback callback) { 280 | this.messageCallbacks.add(callback); 281 | return this; 282 | } 283 | 284 | /** 285 | * Register a callback for SocketEvent.OPEN events 286 | * 287 | * @param callback The callback to receive OPEN events 288 | * @return This Socket instance 289 | */ 290 | public Socket onOpen(final ISocketOpenCallback callback) { 291 | cancelReconnectTimer(); 292 | this.socketOpenCallbacks.add(callback); 293 | return this; 294 | } 295 | 296 | /** 297 | * Sends a message envelope on this socket 298 | * 299 | * @param envelope The message envelope 300 | * @return This socket instance 301 | * @throws IOException Thrown if the message cannot be sent 302 | */ 303 | public Socket push(final Envelope envelope) throws IOException { 304 | final ObjectNode node = objectMapper.createObjectNode(); 305 | node.put("topic", envelope.getTopic()); 306 | node.put("event", envelope.getEvent()); 307 | node.put("ref", envelope.getRef()); 308 | node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); 309 | final String json = objectMapper.writeValueAsString(node); 310 | 311 | log.trace("push: {}, isConnected:{}, JSON:{}", envelope, isConnected(), json); 312 | 313 | RequestBody body = RequestBody.create(MediaType.parse("text/xml"), json); 314 | 315 | if (this.isConnected()) { 316 | webSocket.send(json); 317 | } else { 318 | this.sendBuffer.add(body); 319 | } 320 | 321 | return this; 322 | } 323 | 324 | /** 325 | * Should the socket attempt to reconnect if websocket.onFailure is called. 326 | * 327 | * @param reconnectOnFailure reconnect value 328 | */ 329 | public void reconectOnFailure(final boolean reconnectOnFailure) { 330 | this.reconnectOnFailure = reconnectOnFailure; 331 | } 332 | 333 | /** 334 | * Removes the specified channel if it is known to the socket 335 | * 336 | * @param channel The channel to be removed 337 | */ 338 | public void remove(final Channel channel) { 339 | synchronized (channels) { 340 | for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) { 341 | if (chanIter.next() == channel) { 342 | chanIter.remove(); 343 | break; 344 | } 345 | } 346 | } 347 | } 348 | 349 | public void removeAllChannels() { 350 | synchronized (channels) { 351 | channels.clear(); 352 | } 353 | } 354 | 355 | @Override 356 | public String toString() { 357 | return "PhoenixSocket{" + 358 | "endpointUri='" + endpointUri + '\'' + 359 | ", channels(" + channels.size() + ")=" + channels + 360 | ", refNo=" + refNo + 361 | ", webSocket=" + webSocket + 362 | '}'; 363 | } 364 | 365 | synchronized String makeRef() { 366 | int val = refNo++; 367 | if (refNo == Integer.MAX_VALUE) { 368 | refNo = 0; 369 | } 370 | return Integer.toString(val); 371 | } 372 | 373 | private void cancelHeartbeatTimer() { 374 | if (Socket.this.heartbeatTimerTask != null) { 375 | Socket.this.heartbeatTimerTask.cancel(); 376 | } 377 | } 378 | 379 | private void cancelReconnectTimer() { 380 | if (Socket.this.reconnectTimerTask != null) { 381 | Socket.this.reconnectTimerTask.cancel(); 382 | } 383 | } 384 | 385 | private void flushSendBuffer() { 386 | while (this.isConnected() && !this.sendBuffer.isEmpty()) { 387 | final RequestBody body = this.sendBuffer.remove(); 388 | this.webSocket.send(body.toString()); 389 | } 390 | } 391 | 392 | /** 393 | * Sets up and schedules a timer task to make repeated reconnect attempts at configured 394 | * intervals 395 | */ 396 | private void scheduleReconnectTimer() { 397 | cancelReconnectTimer(); 398 | cancelHeartbeatTimer(); 399 | 400 | Socket.this.reconnectTimerTask = new TimerTask() { 401 | @Override 402 | public void run() { 403 | log.trace("reconnectTimerTask run"); 404 | try { 405 | Socket.this.connect(); 406 | } catch (Exception e) { 407 | log.error("Failed to reconnect to " + Socket.this.wsListener, e); 408 | } 409 | } 410 | }; 411 | timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS); 412 | } 413 | 414 | private void startHeartbeatTimer() { 415 | Socket.this.heartbeatTimerTask = new TimerTask() { 416 | @Override 417 | public void run() { 418 | log.trace("heartbeatTimerTask run"); 419 | if (Socket.this.isConnected()) { 420 | try { 421 | Envelope envelope = new Envelope("phoenix", "heartbeat", 422 | new ObjectNode(JsonNodeFactory.instance), Socket.this.makeRef()); 423 | Socket.this.push(envelope); 424 | } catch (Exception e) { 425 | log.error("Failed to send heartbeat", e); 426 | } 427 | } 428 | } 429 | }; 430 | 431 | timer.schedule(Socket.this.heartbeatTimerTask, Socket.this.heartbeatInterval, 432 | Socket.this.heartbeatInterval); 433 | } 434 | 435 | private void triggerChannelError() { 436 | synchronized (channels) { 437 | for (final Channel channel : channels) { 438 | channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null); 439 | } 440 | } 441 | } 442 | 443 | static String replyEventName(final String ref) { 444 | return "chan_reply_" + ref; 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/SocketEvent.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | public enum SocketEvent { 4 | OPEN, 5 | CLOSE, 6 | ERROR, 7 | MESSAGE 8 | } -------------------------------------------------------------------------------- /src/main/java/org/phoenixframework/channels/SocketState.java: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels; 2 | 3 | /** 4 | * Created by Eoin on 24/04/2015. 5 | */ 6 | public enum SocketState { 7 | CONNECTING, 8 | OPEN, 9 | CLOSING, 10 | CLOSED 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/logging.properties: -------------------------------------------------------------------------------- 1 | handlers=java.util.logging.ConsoleHandler 2 | 3 | .level=INFO 4 | # Handlers 5 | # ----------------------------------------- 6 | 7 | # --- ConsoleHandler --- 8 | # Override of global logging level 9 | java.util.logging.ConsoleHandler.level=INFO 10 | java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter 11 | 12 | org.phoenixframework.channels.level=INFO 13 | -------------------------------------------------------------------------------- /src/main/resources/sample_exchange.js: -------------------------------------------------------------------------------- 1 | var exchanges = [ 2 | { 3 | "topic" : "rooms:lobby", 4 | "event" : "phx_join", 5 | "payload" : 6 | { 7 | }, 8 | "ref" : "1" 9 | }, 10 | { 11 | "topic" : "rooms:lobby", 12 | "ref" : null, 13 | "payload" : 14 | { 15 | "status" : "ok", 16 | "response" : 17 | { 18 | }, 19 | "ref" : "1" 20 | }, 21 | "event" : "phx_reply" 22 | }, 23 | { 24 | "topic" : "rooms:lobby", 25 | "event" : "new_msg", 26 | "payload" : 27 | { 28 | "body" : "Eoin" 29 | }, 30 | "ref" : "2" 31 | }, 32 | { 33 | "topic" : "rooms:lobby", 34 | "ref" : null, 35 | "payload" : 36 | { 37 | "status" : "ok", 38 | "response" : 39 | { 40 | "updated_at" : "2015-04-24T05:26:13Z", 41 | "room_id" : "lobby", 42 | "inserted_at" : "2015-04-24T05:26:13Z", 43 | "id" : 6, 44 | "body" : "Eoin", 45 | "__meta__" : 46 | { 47 | "state" : "loaded", 48 | "source" : "messages" 49 | } 50 | }, 51 | "ref" : "2" 52 | }, 53 | "event" : "phx_reply" 54 | }, 55 | { 56 | "topic" : "rooms:lobby", 57 | "ref" : null, 58 | "payload" : 59 | { 60 | }, 61 | "event" : "ping" 62 | }, 63 | { 64 | "topic" : "rooms:lobby", 65 | "event" : "new_msg", 66 | "payload" : 67 | { 68 | "body" : "Shanaghy" 69 | }, 70 | "ref" : "3" 71 | }, 72 | { 73 | "topic" : "rooms:lobby", 74 | "ref" : null, 75 | "payload" : 76 | { 77 | "status" : "ok", 78 | "response" : 79 | { 80 | "updated_at" : "2015-04-24T05:26:16Z", 81 | "room_id" : "lobby", 82 | "inserted_at" : "2015-04-24T05:26:16Z", 83 | "id" : 7, 84 | "body" : "Shanaghy", 85 | "__meta__" : 86 | { 87 | "state" : "loaded", 88 | "source" : "messages" 89 | } 90 | }, 91 | "ref" : "3" 92 | }, 93 | "event" : "phx_reply" 94 | }, 95 | { 96 | "topic" : "rooms:lobby", 97 | "ref" : null, 98 | "payload" : 99 | { 100 | }, 101 | "event" : "ping" 102 | }, 103 | { 104 | "topic" : "rooms:lobby", 105 | "ref" : null, 106 | "payload" : 107 | { 108 | }, 109 | "event" : "ping" 110 | }, 111 | { 112 | "topic" : "rooms:lobby", 113 | "ref" : null, 114 | "payload" : 115 | { 116 | }, 117 | "event" : "ping" 118 | }, 119 | { 120 | "topic" : "rooms:lobby", 121 | "ref" : null, 122 | "payload" : 123 | { 124 | }, 125 | "event" : "ping" 126 | }, 127 | { 128 | "topic" : "rooms:lobby", 129 | "ref" : null, 130 | "payload" : 131 | { 132 | }, 133 | "event" : "ping" 134 | }, 135 | { 136 | "topic" : "phoenix", 137 | "event" : "heartbeat" 138 | } 139 | ]; -------------------------------------------------------------------------------- /src/main/test/org/phoenixframework/channels/SocketITest.groovy: -------------------------------------------------------------------------------- 1 | package org.phoenixframework.channels 2 | 3 | import spock.lang.Specification 4 | import spock.util.concurrent.BlockingVariable 5 | 6 | class SocketSpec extends Specification { 7 | 8 | def socket = new Socket("ws://localhost:4000/socket/websocket") 9 | 10 | def socketOpenCallback = Mock(ISocketOpenCallback) 11 | def socketCloseCallback = Mock(ISocketCloseCallback) 12 | def socketMessageCallback= Mock(IMessageCallback) 13 | def socketErrorCallback = Mock(IErrorCallback) 14 | 15 | def setup() { 16 | socket.onOpen(socketOpenCallback) 17 | .onClose(socketCloseCallback) 18 | .onMessage(socketMessageCallback) 19 | .onError(socketErrorCallback) 20 | } 21 | 22 | def cleanup() { 23 | socket.disconnect() 24 | } 25 | 26 | def "Socket connects"() { 27 | setup() 28 | when: 29 | socket.connect() 30 | then: 31 | 1 * socketOpenCallback.onOpen() 32 | } 33 | 34 | def "Channel subscribe"() { 35 | setup() 36 | def envelope = new BlockingVariable() 37 | def callback = new IMessageCallback() { 38 | @Override 39 | void onMessage(Envelope e) { 40 | envelope.set(e) 41 | } 42 | } 43 | 44 | when: 45 | socket.connect() 46 | socket.chan("rooms:lobby", null).join().receive("ok", callback) 47 | then: 48 | envelope.get() != null 49 | envelope.get().getTopic() == "rooms:lobby" 50 | } 51 | } --------------------------------------------------------------------------------