Skip to content

Commit

Permalink
Added java version of library
Browse files Browse the repository at this point in the history
  • Loading branch information
Gurgen committed Sep 26, 2017
1 parent 8e31604 commit 39a0c52
Show file tree
Hide file tree
Showing 15 changed files with 394 additions and 16 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ dependencies {
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.google.code.gson:gson:2.8.1'
implementation project(path: ':dotnetcoresignalrclient')
implementation project(path: ':dotnetcoresignalrclientjava')
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.google.gson.Gson
import com.smartarmenia.dotnetcoresignalrclient.*
import com.smartarmenia.dotnetcoresignalrclientjava.*
import kotlinx.android.synthetic.main.activity_main.*


Expand All @@ -29,7 +29,7 @@ class MainActivity : AppCompatActivity(), HubConnectionListener, HubEventListene

}

private val connection: HubConnection = WebSocketHubConnection("http://192.168.0.109:5002/signalr/hubs/auth")
private val connection: HubConnection = WebSocketHubConnection("http://192.168.0.104:5002/signalr/hubs/auth")

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.*
import javax.net.ssl.HttpsURLConnection

class WebSocketHubConnection(private val hubUrl: String) : HubConnection {
companion object {
Expand All @@ -27,25 +26,25 @@ class WebSocketHubConnection(private val hubUrl: String) : HubConnection {
private val listeners = mutableListOf<HubConnectionListener>()
private val eventListeners = mutableMapOf<String, MutableList<HubEventListener>>()
private val parsedUri = Uri.parse(hubUrl)
private val gson = Gson()

override fun connect(authHeader: String?) {
Log.i(TAG, "Requesting connection id...")
val connection: HttpURLConnection = when {
parsedUri.scheme == "http" -> URL(hubUrl).openConnection() as HttpURLConnection
parsedUri.scheme == "https" -> URL(hubUrl).openConnection() as HttpsURLConnection
else -> throw RuntimeException("URL must start with http or https")
}
if (!(parsedUri.scheme == "http" || parsedUri.scheme == "https"))
throw RuntimeException("URL must start with http or https")

val connection: HttpURLConnection = URL(hubUrl).openConnection() as HttpURLConnection
if (authHeader != null) {
connection.addRequestProperty("Authorization", authHeader)
}
connection.connectTimeout = 15000
connection.connectTimeout = 15000
connection.readTimeout = 15000
connection.requestMethod = "OPTIONS"
val responseCode = connection.responseCode
when (responseCode) {
200 -> {
val result = InputStreamConverter.convert(connection.inputStream)
val jsonElement = Gson().fromJson<JsonElement>(result, JsonElement::class.java)
val jsonElement = gson.fromJson<JsonElement>(result, JsonElement::class.java)
val connectionId = jsonElement.asJsonObject.get("connectionId").asString
if (!jsonElement.asJsonObject.get("availableTransports").asJsonArray.toList().map { it.asString }.contains("WebSockets")) {
throw RuntimeException("The server does not support WebSockets transport")
Expand All @@ -60,7 +59,7 @@ class WebSocketHubConnection(private val hubUrl: String) : HubConnection {
private fun connectClient(connectionId: String?, authHeader: String?) {
val uriBuilder = parsedUri.buildUpon()
uriBuilder.appendQueryParameter("id", connectionId)
uriBuilder.scheme(if (parsedUri.scheme == "http") "ws" else "wss")
uriBuilder.scheme(parsedUri.scheme.replace("http", "ws"))
val uri = uriBuilder.build()
val headers = if (authHeader == null) null else mapOf("Authorization" to authHeader)
client = object : WebSocketClient(URI(uri.toString()), Draft_6455(), headers, 15000) {
Expand All @@ -72,7 +71,7 @@ class WebSocketHubConnection(private val hubUrl: String) : HubConnection {

override fun onMessage(s: String) {
Log.i(TAG, s)
val element = Gson().fromJson<SignalRMessage>(s.replace(SPECIAL_SYMBOL, ""), SignalRMessage::class.java)
val element = gson.fromJson<SignalRMessage>(s.replace(SPECIAL_SYMBOL, ""), SignalRMessage::class.java)
if (element.type == 1) {
val message = HubMessage(element.invocationId!!, element.target!!, element.arguments!!)
listeners.forEach { it.onMessage(message) }
Expand All @@ -81,7 +80,7 @@ class WebSocketHubConnection(private val hubUrl: String) : HubConnection {
}

override fun onClose(i: Int, s: String, b: Boolean) {
Log.i(TAG, "Closed. Code: $i, $s, $b")
Log.i(TAG, "Closed. Code: $i, Reason: $s, Remote: $b")
listeners.forEach { it.onDisconnected() }
}

Expand Down Expand Up @@ -121,7 +120,7 @@ class WebSocketHubConnection(private val hubUrl: String) : HubConnection {

override fun invoke(event: String, vararg parameters: Any) {
val map = mapOf("type" to 1, "invocationId" to UUID.randomUUID().toString(), "target" to event, "arguments" to parameters, "nonblocking" to false)
client.send(Gson().toJson(map) + SPECIAL_SYMBOL)
client.send(gson.toJson(map) + SPECIAL_SYMBOL)
}

override fun addListener(listener: HubConnectionListener) {
Expand Down
1 change: 1 addition & 0 deletions dotnetcoresignalrclientjava/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
29 changes: 29 additions & 0 deletions dotnetcoresignalrclientjava/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
apply plugin: 'com.android.library'

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"


defaultConfig {
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"

}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'org.java-websocket:Java-WebSocket:1.3.4'
implementation 'com.google.code.gson:gson:2.8.1'
}
21 changes: 21 additions & 0 deletions dotnetcoresignalrclientjava/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
2 changes: 2 additions & 0 deletions dotnetcoresignalrclientjava/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.smartarmenia.dotnetcoresignalrclientjava" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.smartarmenia.dotnetcoresignalrclientjava;

public interface HubConnection {
void connect(String authHeader);

void disconnect();

void addListener(HubConnectionListener listener);

void removeListener(HubConnectionListener listener);

void subscribeToEvent(String eventName, HubEventListener eventListener);

void unSubscribeFromEvent(String eventName, HubEventListener eventListener);

void invoke(String event, Object... parameters);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.smartarmenia.dotnetcoresignalrclientjava;

public interface HubConnectionListener {
void onConnected();

void onDisconnected();

void onMessage(HubMessage message);

void onError(Exception exception);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.smartarmenia.dotnetcoresignalrclientjava;

public interface HubEventListener {
void onEventMessage(HubMessage message);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.smartarmenia.dotnetcoresignalrclientjava;

import com.google.gson.JsonElement;

public class HubMessage {
private String invocationId = "";
private String target = "";
private JsonElement[] arguments;

public HubMessage(String invocationId, String target, JsonElement[] arguments) {
this.invocationId = invocationId;
this.target = target;
this.arguments = arguments;
}

public String getInvocationId() {
return invocationId;
}

public void setInvocationId(String invocationId) {
this.invocationId = invocationId;
}

public String getTarget() {
return target;
}

public void setTarget(String target) {
this.target = target;
}

public JsonElement[] getArguments() {
return arguments;
}

public void setArguments(JsonElement[] arguments) {
this.arguments = arguments;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.smartarmenia.dotnetcoresignalrclientjava;

import com.google.gson.JsonElement;

public class SignalRMessage {
private String invocationId;
private Integer type;
private String target;
private Boolean nonBlocking;
private JsonElement[] arguments;

public String getInvocationId() {
return invocationId;
}

public void setInvocationId(String invocationId) {
this.invocationId = invocationId;
}

public Integer getType() {
return type;
}

public void setType(Integer type) {
this.type = type;
}

public String getTarget() {
return target;
}

public void setTarget(String target) {
this.target = target;
}

public Boolean getNonBlocking() {
return nonBlocking;
}

public void setNonBlocking(Boolean nonBlocking) {
this.nonBlocking = nonBlocking;
}

public JsonElement[] getArguments() {
return arguments;
}

public void setArguments(JsonElement[] arguments) {
this.arguments = arguments;
}
}
Loading

0 comments on commit 39a0c52

Please sign in to comment.