GitterJavaSDK


Source link: https://github.com/Gitteroid/GitterJavaSDK

Gitter.im Java SDK

👍 Fully compatible with Android

Async :

Sync :

Rx :

Gitter.im Java SDK that facilitates communication with Gitter API, Gitter Streaming API, Gitter Faye API.

It provides three approaches to work with API:

  • RxJava approach;
  • Async (callback) approach.
  • Sync approach.

Table of content

### Setup Add gradle dependency:

For RxJava:

repositories {

 jcenter() 
}
  dependencies {

 compile 'com.github.amatkivskiy:gitter.sdk.rx:1.6.0' 
}

For async:

repositories {

 jcenter() 
}
  dependencies {

 compile 'com.github.amatkivskiy:gitter.sdk.async:1.6.0' 
}

For sync:

repositories {

 jcenter() 
}
  dependencies {

 compile 'com.github.amatkivskiy:gitter.sdk.sync:1.6.0' 
}

###Release notes

  • 1.6.0 (12.01.2017)
    • RoomResponse:

      • Remove favouriteOrder
      • Add avatarUrl
      • Add groupId
      • Add public
      • Add activity
      • Add premium
    • UserResponse:

      • Add avatarUrl
      • Add role
      • Add staff
    • Rx,Async,Sync:

      • Add delete room API
      • Remove channels API
      • Fix joinRoom API
      • Add getRoomById API
      • Add getBannedusers API
      • Add banUser API
      • Add unBanUser API
      • Add Welcome API support
    • Faye

      • Update OkHttp to version 3.5.0
  • 1.5.1 (07.05.2016)
    • Updated RoomRepsonse data structure.
    • Added aroundId and q params for chat messages request.
    • Added Update room request.
    • Fixed Issue data structure type.
    • Faye: added ability to set custom OkHttpClient.
    • Faye: changed onSubscribed() params, no it passes messages snapshots.
  • 1.5 (14.01.2016)
    • Added faye api support.
    • Added room events streaming api support.
  • 1.4
    • Refactored library structure
    • Added async api support.
    • Added async api samples.
    • Added sync api support.
    • Added sync api samples.
  • 1.2.1
    • Added ability to retrieve unread messages.
  • 1.2.0
    • Added ability to search users
    • Added ability to search rooms
    • Added ability to leave room
  • 1.1.0
    • Added room messages streaming API.

###Features

  • Authentication

Rooms resource

  • List rooms
  • Room users
  • Channels
  • Join a room
  • Remove user from the room
  • Leave room
  • Search rooms

User resource

  • Current user
  • User rooms
  • User orgs
  • User repos
  • User channels
  • Search users

Messages resource

  • Unread items
  • List messages
  • Send a message
  • Update a message

❗? Streaming (Avalible only in Rx part.)

  • Room messages stream
  • Room events stream

❗? Faye API (Avalible only in Async part.)

  • Room messages events
  • Room user presence events
  • Room user managment events

###Description

Authentication Please read Authentication article on Gitter Developer before.

How to authenticate user with SDK

  1. Setup GitterDeveloperCredentials with info from here:
GitterDeveloperCredentials.init(new SimpleGitterCredentialsProvider(your_oauth_key, your_oauth_secret, your_redirect_url));
  1. Get Gitter request access URL:
String gitterAccessUrl = GitterOauthUtils.buildOauthUrl();
  1. Open this url in something like embedded browser and listen for redirects.
  2. When user grants access gitter redirects back with url like:
http://some.redirect.url?code=deadbeef 

extract code parameter value.

  1. Exchange code for access token:
  • Rx:
RxGitterAuthenticationClient authenticationClient = new RxGitterAuthenticationClient.Builder().build();
  authenticationClient.getAccessToken(code).subscribe(new Action1<AccessTokenResponse>() {

 @Override

 public void call(AccessTokenResponse accessTokenResponse) {

System.out.println("Access token = " + accessTokenResponse.accessToken);

 
}

  
}
);
  • Async:
AsyncGitterAuthenticationClient authenticationClient = new AsyncGitterAuthenticationClient.Builder()

.build();
  authenticationClient.getAccessToken(code, new Callback<AccessTokenResponse>() {

  @Override

public void success(AccessTokenResponse tokenResponse, Response response) {

System.out.println("Access token = " + accessTokenResponse.accessToken);

}

 @Override

public void failure(RetrofitError error) {

}
 
}
);
  • Sync:
SyncGitterAuthenticationClient authenticationClient = new SyncGitterAuthenticationClient.Builder()

.build();
  AccessTokenResponse accessTokenResponse = authenticationClient.getAccessToken(code);
 System.out.println("Access token = " + accessTokenResponse.accessToken);
 
  1. Save and use this accessToken to make requests to the REST API.

How to get data from Gitter REST API

  1. Create GitterApiClient with help of GitterApiClient.Builder:
  • Rx:
RxGitterApiClient client = new RxGitterApiClient.Builder()

.withAccountToken("user_access_token")

.build();
  • Async:
AsyncGitterApiClient client = new AsyncGitterApiClient.Builder()

.withAccountToken("user_access_token")

.build();
 
  • Sync:
SyncGitterApiClient client = new SyncGitterApiClient.Builder()

.withAccountToken("user_access_token")

.build();
 

also you can provide some Retrofit config for requests (same for Rx and Async):

RxGitterApiClient client = new RxGitterApiClient.Builder()

.withAccountToken("user_access_token")

.withClient(new OkClient())

.withExecutors(httpExecutor, callbackExecutor)

.withLogLevel(RestAdapter.LogLevel.BASIC)

.build();
  1. Execute any request that you need:
  • Rx:
client.getCurrentUser().subscribe(new Action1<UserResponse>() {

 @Override

 public void call(UserResponse user) {

System.out.println("user.displayName = " + user.displayName);

 
}

  
}
);
  • Async:
client.getCurrentUser(new Callback<UserResponse>() {

 @Override

 public void success(UserResponse userResponse, Response response) {

System.out.println("userResponse.displayName = " + userResponse.displayName);

 
}

  @Override

 public void failure(RetrofitError error) {

System.err.println("error = " + error);

 
}

  
}
);
  • Sync:
UserResponse userResponse = client.getCurrentUser();
 System.out.println("userResponse.displayName = " + userResponse.displayName);

or

  • Rx:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
 String roomId = "room_id";  client.getRoomMessages(roomId, params).subscribe(new Action1<List<MessageResponse>>() {

 @Override

 public void call(List<MessageResponse> messages) {

System.out.println("Received " + messages.size() + " messages");

 
}

  
}
);
  • Async:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
 String roomId = "room_id";  client.getRoomMessages(roomId, params, new Callback<List<MessageResponse>>() {

 @Override

 public void success(List<MessageResponse> messages, Response response) {

System.out.println("Received " + messages.size() + " messages");

 
}

  @Override

 public void failure(RetrofitError error) {

}

  
}
);
  • Sync:
ChatMessagesRequestParams params = new ChatMessagesRequestParamsBuilder().limit(20).build();
 String roomId = "room_id";  List<MessageResponse> messages = client.getRoomMessages(roomId, params);
 System.out.println("Received " + messages.size() + " messages");

or

  • Rx:
client.getUserChannels("user_id").subscribe(new Action1<List<RoomResponse>>() {

 @Override

 public void call(List<RoomResponse> rooms) {

System.out.println("Received " + rooms.size() + " rooms");

 
}

  
}
);
  • Async:
client.getUserChannels("user_id", new Callback<List<RoomResponse>>() {

 @Override

 public void success(List<RoomResponse> rooms, Response response) {

System.out.println("Received " + rooms.size() + " rooms");

 
}

  @Override

 public void failure(RetrofitError error) {

}

  
}
);
  • Sync:
List<RoomResponse> rooms = client.getUserChannels("user_id");
 System.out.println("Received " + rooms.size() + " rooms");

### How to get streaming data from Gitter Streaming API

❗? Please don't set any log level for RxGitterStreamingApiClient as it blocks the stream.

❗? If you get java.net.SocketTimeoutException: Read timed out try to encrease ReadTimeout in your retrofit.client.Client and spicify this client for GutterApiClient ( withClient()).

RxGitterStreamingApiClient client = new RxGitterStreamingApiClient.Builder()

.withAccountToken("user_access_token")

.build();
  String roomId = "room_id";  client.getRoomMessagesStream(roomId).subscribe(new Action1<MessageResponse>() {
  @Override  public void call(MessageResponse messageResponse) {

System.out.println("messageResponse = " + messageResponse);
  
}
 
}
);

or

RxGitterStreamingApiClient client = new RxGitterStreamingApiClient.Builder()

.withAccountToken("user_access_token")

.build();
  String roomId = "room_id";  client.getRoomEventsStream(roomId).subscribe(new Action1<RoomEvent>() {
  @Override  public void call(RoomEvent event) {

System.out.println(event.sent);

 System.out.println(event.meta);
  
}
 
}
);

###How to work with Gitter Faye API

1 Setup AsyncGitterFayeClient:

AsyncGitterFayeClient client = new AsyncGitterFayeClientBuilder()

.withAccountToken("account_token")

.withOnDisconnected(new DisconnectionListener() {

  @Override

  public void onDisconnected() {

 // Client has disconnected. You can reconnect it here.

  
}

}
)

.withOkHttpClient(new OkHttpClient())

.build();

2 Connect it to the server:

client.connect(new ConnectionListener() {

 @Override

 public void onConnected() {

// Client is ready. Subscribe to channels you are intereseted in.

 
}

  
}
);

3 Subscribe to desighed channel:

client.subscribe(new RoomMessagesChannel("room_id") {

  @Override

  public void onMessage(String channel, MessageEvent message) {

 // Yeah, you've got message here.

  
}
 
}
);

or

client.subscribe(new RoomUserPresenceChannel("room_id") {

  @Override

  public void onMessage(String channel, UserPresenceEvent message) {

 // User is active or not.

  
}
 
}
);

or

client.subscribe(new RoomUsersChannel("room_id") {

  @Override

  public void onMessage(String channel, UserEvent message) {

 // User left ot joined the room.

  
}
 
}
);

or define your custom channel:

client.subscribe("channel_name",new ChannelListener(){
 @Override public void onMessage(String channel,JsonObject message){
 //

  Handle message here.
  
}
  @Override public void onFailed(String channel,Exception ex){

  
}
  @Override public void onSubscribed(String channel, List<MessageResponse> messagesSnapshot){

  
}
  @Override public void onUnSubscribed(String channel){

  
}

  
}
);

You can unsubscribe from channel:

client.unSubscribe("channel_name");

or

RoomMessagesChannel channel = new RoomMessagesChannel("room_id") {

@Override

public void onMessage(String channel, MessageEvent message) {

}
 
}
; client.subscribe(channel);
  client.unSubscribe(channel);

Finally when your are finished with client, you need to call:

client.disconnect();

Thats all =).

###Samples

You can see some code samples here

Feel free to ask any questions.

LICENSE

The MIT License (MIT)  Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

Resources

Starter boilerplate projects for Android, with Components Architecture implemented, written completely in Kotlin. Variations include Rx, Realm & Dagger usage.

Neuronizer offers the opportunity to order your thoughts, ideas and tasks in categories to recognise the information you need as fast as possible.

Features

  • Add, remove and update notes
  • Add, remove and update ToDo lists
  • Sort everything as you wish
  • Designed for simple and fast usage
  • Encrypted storage of data, on device only
  • Create widgets
  • Categorisation in ToDo lists
  • Mark tasks as done
  • Add details to each task
  • Share ToDo lists

The library is a small widget for image cropping in Instagram-like style. Written in Kotlin.

Type-safe time calculations in Kotlin.

Image loader library for Android. Allows you to build your own image loader that will do exactly what you want. Almost unlimited customization.

An extension of EditText with pin style written in Kotlin.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes