Skip to content

Repository files navigation

actioncable-client-java

Build StatusRelease

This is the actioncable client library for Java. Please see Action Cable Overview to understand actioncable itself.

Usage

Gradle

repositories {
jcenter()
maven { url "https://jitpack.io" }
}
dependencies {
implementation 'com.github.hosopy:actioncable-client-java:0.1.2'
}

This Library uses google/gson to parse and compose JSON strings.

Please see user guide to know about GSON API.

Basic

// 1. SetupURIuri = newURI("ws://cable.example.com");
Consumerconsumer = ActionCable.createConsumer(uri);
// or specify some optionsURIuri = newURI("ws://cable.example.com");
Consumer.Optionsoptions = newConsumer.Options();
options.reconnection = true;
options.pingInterval = 30l;
options.pingTimeUnit = TimeUnit.SECONDS;
Consumerconsumer = ActionCable.createConsumer(uri, options);
// 2. Create subscriptionChannelappearanceChannel = newChannel("AppearanceChannel");
Subscriptionsubscription = consumer.getSubscriptions().create(appearanceChannel);
subscription
.onConnected(newSubscription.ConnectedCallback() {
@Overridepublicvoidcall() {
// Called when the subscription has been successfully completed
}
}).onRejected(newSubscription.RejectedCallback() {
@Overridepublicvoidcall() {
// Called when the subscription is rejected by the server
}
}).onReceived(newSubscription.ReceivedCallback() {
@Overridepublicvoidcall(JsonElementdata) {
// Called when the subscription receives data from the server
}
}).onDisconnected(newSubscription.DisconnectedCallback() {
@Overridepublicvoidcall() {
// Called when the subscription has been closed
}
}).onFailed(newSubscription.FailedCallback() {
@Overridepublicvoidcall(ActionCableExceptione) {
// Called when the subscription encounters any error
}
});
// 3. Establish connectionconsumer.connect();
if(consumer.isConnected()) {
System.out.println("Consumer connected!");
}
// 4. Perform any actionsubscription.perform("away");
// 5. Perform any action using JsonObject(GSON)JsonObjectparams = newJsonObject();
params.addProperty("foo", "bar");
subscription.perform("appear", params);
// 6. Unsubscribe & close connectionconsumer.unsubscribeAndDisconnect();

Passing Parameters to Channel

ChannelchatChannel = newChannel("ChatChannel");
chatChannel.addParam("room", "Best Room");
Subscriptionsubscription = consumer.getSubscriptions().create(chatChannel);

Supported parameter type is Number, String, Boolean and JsonElement(GSON).

chatChannel.addParam("room_id", 1);
chatChannel.addParam("room", "Best Room");
chatChannel.addParam("private", true);
chatChannel.addParam("params", newJsonObject());

Custom Subscription Interface

You can perform any action by calling Subscription#perform(), but you can define custom interfaces having methods.

publicinterfaceChatSubscriptionextendsSubscription {
/* * Equivalent: * perform("join") */@Perform("join")
voidjoin();
/* * Equivalent: * perform("send_message", JsonObjectFactory.fromJson("{body: \"...\", private: true}")) */@Perform("send_message")
voidsendMessage(@Data("body") Stringbody, @Data("private") booleanisPrivate);
}

Supported parameter type is Number, String, Boolean and JsonElement(GSON).

To instantiate the custom subscription, pass the interface when you create a subscription.

ChannelchatChannel = newChannel("ChatChannel");
ChatSubscriptionsubscription = consumer.getSubscriptions().create(appearanceChannel, ChatSubscription.class);
consumer.open();
subscription.join();
subscription.sendMessage("Hello", true);

Options

URIuri = newURI("ws://cable.example.com");
Consumer.Optionsoptions = newConsumer.Options();
options.reconnection = true;
Consumerconsumer = ActionCable.createConsumer(uri, options);

Below is a list of available options.

  • sslContext

    options.sslContext = yourSSLContextInstance;
  • hostnameVerifier

    options.hostnameVerifier = yourHostnameVerifier;
  • cookieHandler

    options.cookieHandler = yourCookieManagerInstance;
  • query

    Map<String, String> query = newHashMap();
    query.put("foo", "bar");
    options.query = query;
  • headers

    Map<String, String> headers = newHashMap();
    headers.put("X-FOO", "bar");
    headers.put("Origin", "https://your-origin.tld");
    options.headers = headers;
  • reconnection

    • If reconnection is true, the client attempts to reconnect to the server when underlying connection is stale.
    • Default is false.
    options.reconnection = false;
  • reconnectionMaxAttempts

    • The maximum number of attempts to reconnect.
    • Default is 30.
    options.reconnectionMaxAttempts = 30;
  • okHttpClientFactory

    • Factory instance to create your own OkHttpClient.
    • If okHttpClientFactory is not set, just create OkHttpClient by new OkHttpClient().
    options.okHttpClientFactory = newConnection.Options.OkHttpClientFactory() {
    @OverridepublicOkHttpClientcreateOkHttpClient() {
    finalOkHttpClientclient = newOkHttpClient();
    client.networkInterceptors().add(newStethoInterceptor());
    returnclient;
    }
    };

Authentication

How to authenticate a request depends on the architecture you choose.

Authenticate by HTTP Header

Consumer.Optionsoptions = newConsumer.Options();
Map<String, String> headers = newHashMap();
headers.put("Authorization", "Bearer xxxxxxxxxxx");
options.headers = headers;
Consumerconsumer = ActionCable.createConsumer(uri, options);

Authenticate by Query Params

Consumer.Optionsoptions = newConsumer.Options();
Map<String, String> query = newHashMap();
query.put("access_token", "xxxxxxxxxx");
options.query = query;
Consumerconsumer = ActionCable.createConsumer(uri, options);

Authenticate by Cookie

CookieManagercookieManager = newCookieManager();
// Some setup
...
options.cookieHandler = cookieManager;
Consumerconsumer = ActionCable.createConsumer(uri, options);

Proguard Rules

-keepclasscom.hosopy.actioncable.** { *; }
-keepinterfacecom.hosopy.actioncable._* { *; }

License

MIT

About

Actioncable client library for Java

Topics

Resources

Stars

74 stars

Watchers

8 watching

Forks

Releases

Packages

Contributors

Languages