Coder Social home page Coder Social logo

actioncable-client-java's Introduction

actioncable-client-java

Build Status Release

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 {
    compile '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. Setup
URI uri = new URI("ws://cable.example.com");
Consumer consumer = ActionCable.createConsumer(uri);

// 2. Create subscription
Channel appearanceChannel = new Channel("AppearanceChannel");
Subscription subscription = consumer.getSubscriptions().create(appearanceChannel);

subscription
    .onConnected(new Subscription.ConnectedCallback() {
        @Override
        public void call() {
            // Called when the subscription has been successfully completed
        }
    }).onRejected(new Subscription.RejectedCallback() {
        @Override
        public void call() {
            // Called when the subscription is rejected by the server
        }
    }).onReceived(new Subscription.ReceivedCallback() {
        @Override
        public void call(JsonElement data) {
            // Called when the subscription receives data from the server
        }
    }).onDisconnected(new Subscription.DisconnectedCallback() {
        @Override
        public void call() {
            // Called when the subscription has been closed
        }
    }).onFailed(new Subscription.FailedCallback() {
        @Override
        public void call(ActionCableException e) {
            // Called when the subscription encounters any error
        }
    });

// 3. Establish connection
consumer.connect();

// 4. Perform any action
subscription.perform("away");

// 5. Perform any action using JsonObject(GSON)
JsonObject params = new JsonObject();
params.addProperty("foo", "bar");
subscription.perform("appear", params);

Passing Parameters to Channel

Channel chatChannel = new Channel("ChatChannel");
chatChannel.addParam("room", "Best Room");
Subscription subscription = 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", new JsonObject());

Custom Subscription Interface

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

public interface ChatSubscription extends Subscription {
    /*
     * Equivalent:
     *   perform("join")
     */
    @Perform("join")
    void join();

    /*
     * Equivalent:
     *   perform("send_message", JsonObjectFactory.fromJson("{body: \"...\", private: true}"))
     */
    @Perform("send_message")
    void sendMessage(@Data("body") String body, @Data("private") boolean isPrivate);
}

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

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

Channel chatChannel = new Channel("ChatChannel");
ChatSubscription subscription = consumer.getSubscriptions().create(appearanceChannel, ChatSubscription.class);

consumer.open();

subscription.join();
subscription.sendMessage("Hello", true);

Options

URI uri = new URI("ws://cable.example.com");

Consumer.Options options = new Consumer.Options();
options.reconnection = true;

Consumer consumer = 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 = new HashMap();
    query.put("foo", "bar");
    options.query = query;
  • headers

    Map<String, String> headers = new HashMap();
    headers.put("X-FOO", "bar");
    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 = new Connection.Options.OkHttpClientFactory() {
        @Override
        public OkHttpClient createOkHttpClient() {
            final OkHttpClient client = new OkHttpClient();
            client.networkInterceptors().add(new StethoInterceptor());
            return client;
        }
    };

Authentication

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

Authenticate by HTTP Header

Consumer.Options options = new Consumer.Options();

Map<String, String> headers = new HashMap();
headers.put("Authorization", "Bearer xxxxxxxxxxx");
options.headers = headers;

Consumer consumer = ActionCable.createConsumer(uri, options);

Authenticate by Query Params

Consumer.Options options = new Consumer.Options();

Map<String, String> query = new HashMap();
query.put("access_token", "xxxxxxxxxx");
options.query = query;

Consumer consumer = ActionCable.createConsumer(uri, options);

Authenticate by Cookie

CookieManager cookieManager = new CookieManager();
// Some setup
...
options.cookieHandler = cookieManager;

Consumer consumer = ActionCable.createConsumer(uri, options);

License

MIT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.